当然需要注册好七牛云的账号,配置好七牛云。
安装Nuget - MQiniu.Core
获取AccessKey,SecretKey。登录七牛管理后台->个人信息->秘钥管理
public static string Upload(IFormFile file, string fileName) { try { var mac = new Mac(AccessKey, SecretKey); var ex = Path.GetExtension(file.FileName); //后缀 if (ex == null || !((IList)FileTypes.FileType).Contains(ex.ToLower())) return string.Empty; var key = $"{fileName.ToLower()}/{DateTime.Now.Year}/{DateTime.Now:yyyyMMddHHmmssfff}{ex}"; var bucket = Bucket; PutExtra extra = new PutExtra(); PutPolicy putPolicy = new PutPolicy { Scope = bucket }; // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY" // putPolicy.Scope = bucket + ":" + saveKey; //putPolicy.Scope = Bucket; putPolicy.SetExpires(3600); // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认)则不删除 putPolicy.DeleteAfterDays = 1; var token = Qiniu.Util.Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); Config config = new Config { Zone = Zone.ZONE_CN_East, UseHttps = true, UseCdnDomains = true, ChunkSize = ChunkUnit.U512K }; // 设置上传区域 // 设置 http 或者 https 上传 // 表单上传 FormUploader target = new FormUploader(config); HttpResult result = target.UploadStream(file.OpenReadStream(), key, token, extra); if (result.Code == 200) return key; } catch (Exception ex) { LogHelper.Error($"qiniu:{ex.ToString()}"); return string.Empty; } return string.Empty; } private static class FileTypes { public static readonly string[] FileType = { ".jpg", ".png", ".jpeg", ".gif", ".bmp" }; }