先要下载一个MQiniu.CoreSdk包
ak、sk为七牛云的秘钥,在个人中心查看
public IActionResult Upload(List<IFormFile> formFiles)
{
//先上传到本地,才能上传到七牛云,上传完成后本地的文件可删除
var res = Task.Run(() =>
{
//ak修改为自己的accessKey
//sk修改为自己的secretKey
Mac mac = new Mac("Nm97OmZGM_hvzQGay45jZEqX-f-B1UGlknUQHcnx", "m4rSY8DcJqWw4X8-IFtXW2YTRoCzAdwDcK2pCi4S");
List<string> result = new List<string>();
foreach (var formFile in formFiles)
{
if (formFile.Length > 0)
{
var filePath_temp = $"{AppContext.BaseDirectory}/Images_temp";
var fileName = $"{DateTime.Now:yyyyMMddHHmmssffff}{formFile.FileName}";
if (!Directory.Exists(filePath_temp))
{
Directory.CreateDirectory(filePath_temp);
}
using (var stream = System.IO.File.Create($"{filePath_temp}/{fileName}"))
{
formFile.CopyTo(stream);
}
// 上传文件名
string key = fileName;
// 本地文件路径
string filePath = $"{filePath_temp}/{fileName}";
// 存储空间名
//修改成自己的命名空间
string Bucket = "mes1";
// 设置上传策略
PutPolicy putPolicy = new PutPolicy();
// 设置要上传的目标空间
putPolicy.Scope = Bucket;
// 上传策略的过期时间(单位:秒)
//putPolicy.SetExpires(3600);
// 文件上传完毕后,在多少天后自动被删除
//putPolicy.DeleteAfterDays = 1;
// 生成上传token
string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
Config config = new Config();
// 设置上传区域 ZONE_CN_South
//改成自己所在的域名
config.Zone = Zone.ZONE_CN_South;
// 设置 http 或者 https 上传
config.UseHttps = true;
config.UseCdnDomains = true;
config.ChunkSize = ChunkUnit.U512K;
// 表单上传
FormUploader target = new FormUploader(config);
HttpResult httpResult = target.UploadFile(filePath, key, token, null);
result.Add(fileName);
//删除备份文件夹
Directory.Delete(filePath_temp, true);
}
}
return string.Join(",", result);
});
return Ok(res);
}
标签:putPolicy,七牛云,string,temp,filePath,C#,config,配置,上传
From: https://www.cnblogs.com/wangsr/p/18089072