⭐️ obs 上传文件
⭐️ obs 下载文件
🏁 分割线
📖 代码
🌈 java:
package com.hwq.mydemo.obs;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.exception.ObsException;
import com.obs.services.model.AuthTypeEnum;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectRequest;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
/**
* mydemo
*
* @author hwq
* @date 2022/12/28 16:03
**/
@SpringBootTest
@Slf4j
public class FileUpdateTest {
/**
* obs文件上传
*/
@Test
public void testFileUpdate() throws Exception {
String protocol = "https://";
// String endPoint = "obs.cn-south-1.myhuaweicloud.com"; // obs 存储地址
// String ak = "***"; // ak
// String sk = "***"; // sk
// String bucketName = "hwqbucket";
// String objectKey = "hwqtestkey"; // 对象名称
AuthTypeEnum authType = AuthTypeEnum.OBS;
ObsConfiguration config = new ObsConfiguration();
config.setEndPoint(endPoint);
config.setAuthType(authType);
ObsClient obsClient = new ObsClient(ak, sk, config);
PutObjectRequest request = new PutObjectRequest();
request.setBucketName(bucketName);
request.setObjectKey(objectKey);
File sampleFile = createSampleFile();
request.setFile(sampleFile);
PutObjectResult result = obsClient.putObject(request);
log.info("code: "+result.getStatusCode());
}
private File createSampleFile() throws Exception {
File file = File.createTempFile("hwq", ".txt");
file.deleteOnExit();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("123");
writer.close();
return file;
}
@Test
public void createFileTest() throws Exception {
File sampleFile = createSampleFile();
}
/**
* obs 文件下载
*/
@Test
public void testFileDownload() {
// obs 存储位置
String endPoint = "obs.cn-south-1.myhuaweicloud.com";
String ak = "***";
String sk = "***";
ObsClient obsClient = null;
String bucketName = "hwqbucket";
String objectKey = "hwqtestkey";
// 本地存储地址
String localFilePath = "C:\\Users\\Admin\\AppData\\Local\\Temp\\hwqdir\\hwqobstest.txt";
ObsConfiguration config = new ObsConfiguration();
config.setSocketTimeout(30000);
config.setConnectionTimeout(10000);
config.setEndPoint(endPoint);
try {
// instance obs client
obsClient = new ObsClient(ak, sk, config);
// create bucket
log.info("Create a new bucket ");
// obsClient.createBucket(bucketName);
// download
simpleDownload(obsClient,bucketName,objectKey);
File localFile = new File(localFilePath);
if (!localFile.exists()) {
localFile.getParentFile().mkdirs();
}
log.info("Downloading an object to file :" + localFilePath);
// download the object to a file
downloadToLocalFile(obsClient,bucketName,objectKey,localFilePath);
log.info("deleting object " + objectKey);
//obsClient.deleteObject(bucketName, objectKey, null);
} catch (ObsException e) {
log.error("Response Code : " + e.getResponseCode());
log.error("Error Message: " + e.getErrorMessage());
log.error("Errot Code : " + e.getErrorCode());
log.error("Request ID: " + e.getErrorRequestId());
log.error("Host ID: " + e.getErrorHostId());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (obsClient != null) {
try {
obsClient.close();
} catch (IOException e) {
}
}
}
}
private void simpleDownload(ObsClient obsClient, String bucketName ,String objectKey) throws IOException {
ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
displayTextInputStream(obsObject.getObjectContent());
}
private void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while(true){
String line = reader.readLine();
if (line == null){
break;
}
log.info(line);
}
reader.close();
}
private void downloadToLocalFile(ObsClient obsClient,String bucketName,String objectKey,String localFilePath) throws IOException{
ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
ReadableByteChannel rchannel = Channels.newChannel(obsObject.getObjectContent());
ByteBuffer buffer = ByteBuffer.allocate(4096);
WritableByteChannel wchannel = Channels.newChannel(new FileOutputStream(new File(localFilePath)));
while (rchannel.read(buffer)!= -1){
buffer.flip();
wchannel.write(buffer);
buffer.clear();
}
rchannel.close();
wchannel.close();
}
}
🌈 c# :
#region 上传/下载 obs文件
private static string endpoint = "obs.ap-southeast-1.myhuaweicloud.com";
private static string AK = "****";
private static string SK = "****";
private static string bucketName = "jointech-705c-bucket";
private static ObsClient client;
/// <summary>
/// hwq 2022年12月30日12:11:52
/// 上传文件到obs
/// </summary>
/// <returns></returns>
[HttpPost]
public MBackResult UploadFile2Obs()
{
MBackResult _BackResult = new MBackResult();
try
{
// 上传文件转 byte[]
int count = HttpContext.Current.Request.Files.Count;
if (count > 0)
{
// file 转 stream
HttpPostedFile file = HttpContext.Current.Request.Files[0];
byte[] bytes = new byte[file.ContentLength];
file.InputStream.Read(bytes, 0, bytes.Length);
string str = Encoding.UTF8.GetString(bytes);
Stream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str));
// 获取文件名
string fileName = file.FileName;
// 上传到obs
client = new ObsClient(AK, SK, endpoint);
PutObjectRequest request = new PutObjectRequest()
{
BucketName = bucketName,
ObjectKey = fileName,
InputStream = stream,
};
// .NET 4.0 修改https请求协议
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
PutObjectResponse response = client.PutObject(request);
Dictionary<String, String> dic = new Dictionary<String, String>();
dic.Add("BucketName", bucketName);
dic.Add("ObjectKey", fileName);
// 保存 BucketName 和 ObjectKey 到数据库
// ......
_BackResult.Result = (int)EnumResult.Result200;
_BackResult.Message = JsonConvert.SerializeObject(dic).ToString();
}
else
{
_BackResult.Result = (int)EnumResult.Result102;
_BackResult.Message = "file is null ";
}
}
catch (ObsException ex)
{
_BackResult.Result = (int)EnumResult.Result105;
_BackResult.Message = "fail";
Log.Instance.Error("UploadFileForTest:Exception errorcode:" + ex.ErrorCode + " when upload part." + "Exception errormessage: " + ex.ErrorMessage);
}
return _BackResult;
}
/// <summary>
/// hwq 2022年12月30日12:11:57
/// 下载obs 文件
/// </summary>
[HttpPost]
public MBackResult DownloadFile4Obs(string fileName)
{
MBackResult _BackResult = new MBackResult();
try
{
// 需要参数 bucketName 和 fileName
GetObjectRequest request = new GetObjectRequest()
{
BucketName = bucketName,
ObjectKey = fileName,
};
// ak sk endpoint 可以设置全局变量
client = new ObsClient(AK, SK, endpoint);
// .NET 4.0 修改https请求协议
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
using (GetObjectResponse response = client.GetObject(request))
{
//保存到本地文件 服务器文件路径+文件名
string dest = "F:\\" + fileName;
if (!System.IO.File.Exists(dest))
{
response.WriteResponseStreamToFile(dest);
_BackResult.Result = (int)EnumResult.Result200;
_BackResult.Message = dest;
}
else
{
_BackResult.Result = (int)EnumResult.Result107;
_BackResult.Message = "file is exists";
}
}
}
catch (Exception e)
{
_BackResult.Result = (int)EnumResult.Result105;
_BackResult.Message = "fail";
Log.Instance.Error("downloadFile4Obs is Exception : " + e.Message);
}
return _BackResult;
}
#endregion