一、使用NuGet安装【Aliyun.OSS.SDK】
注意:如果有多个项目,需要在具体使用的项目跟启动项目都安装同一版本的Aliyun.OSS.SDK
二、上传代码
using Aliyun.OSS;
using System.IO;
using System;
using CadApplication.Service.Dto;
using System.Net;
using System.Net.Sockets;
namespace CadApplication.Util
{
public class OSSUtil
{
string accessKeyId = "*******"; // 设置自己的 Access Key ID
string accessKeySecret = "*******"; // 设置自己的 Access Key Secret
string endpoint = "*******aliyuncs.com"; // 设置自己的 Endpoint
string bucketName = "*******"; // 设置自己的 Bucket Name annengcadapitest
/// <summary>
/// 测试OSS.
/// </summary>
public CommonResult<OSSFileInforDto> TestOSS()
{
// 整体逻辑:上传服务器本地文件到阿里云OSS,然后上传成功后再获取OSS文件的存放路径
CommonResult<OSSFileInforDto> result = new CommonResult<OSSFileInforDto>();
// 创建 OssClient 对象
var ossClient = new OssClient("*******.aliyuncs.com", "*******", "*******");
// 获取本地文件路径
string localFilePath = @"C:\Users\*******\Desktop\MonthQuery.txt"; // 设置本地文件路径
// 指定上传到 OSS 的目标文件名称
string fileName = Path.GetFileName(localFilePath);
// OSS的路径 规律 年/月/日 例如:2024/1/20240101
string filePath = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.ToString("yyyy-MM-dd");
string objectName = filePath +"/"+ fileName;
try
{
using (var fs = File.OpenRead(localFilePath))
{
// 调用 PutObjectAsync 方法进行文件上传
var putResult= ossClient.PutObject(bucketName, objectName, fs);
// 说明文件上传成功,然后读取到文件的存放地址,进行返回
if (putResult.HttpStatusCode == HttpStatusCode.OK)
{
GeneratePresignedUriRequest generatePresignedUriRequest = new GeneratePresignedUriRequest(bucketName, objectName);
var uriResult = ossClient.GeneratePresignedUri(generatePresignedUriRequest);
string localHostIp = string.Empty;
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localHostIp = ip.ToString();
}
}
// 然后返回数据的url
OSSFileInforDto oSSFileInforDto = new OSSFileInforDto();
oSSFileInforDto.FileLocalPath = localFilePath;
oSSFileInforDto.FileName = fileName;
oSSFileInforDto.LocalHostIP = localHostIp;
oSSFileInforDto.OSSFileUrl = uriResult.Host + uriResult.AbsolutePath;
result.Data = oSSFileInforDto;
result.Success = true;
result.Message = "上传文件到OSS成功";
}
else
{
result.Success = false;
result.Message = $"上传文件到OSS失败";
}
// var selectResult = ossClient.GeneratePresignedUri(bucketName,);
}
}
catch (Exception ex)
{
result.Success = false;
result.Message = $"上传文件到OSS失败{ex.Message}";
}
finally
{
// 释放资源
// ossClient.shutdown;
}
return result;
}
}
}
三、 遇到问题
3.1 Object reference not set to an instance of an object.
引起这个问题由两个原因:1. 启动项目里面没有安装【Aliyun.OSS.SDK】。2.启动项目里面的【Aliyun.OSS.SDK】跟实际执行代码的项目里面的【Aliyun.OSS.SDK】版本不一致。
3.2 Aliyun.OSS.Common.OssException:The specified bucket does not exist.
没有在OSS上创建Bucket(桶),使用阿里云官方工具OSS Browser 创建,也可以使用代码创建。具体可以参考阿里云官方文档:https://help.aliyun.com/zh/oss/getting-started/sdk-quick-start?spm=a2c4g.11186623.0.0.1db27586JIsQcM