.NET Core項目----七牛雲圖片上傳
阿新 • • 發佈:2018-08-14
arp logs each 重命名 setting ext except his input
在引用官方的qiniu.core的nuget是總是發生錯誤,錯誤如下,所以就在網上找到了一種解決方案,並稍微改進了一番,
以下是引用圖:
第一步:引用nuget(是位大神寫的,官方的qiniu.core用不了)
第二部:新建項目新建控制器視圖、添加配置信息類和讀取配置信息
配置信息類:
public class QnySetting { public string qiniuyunAK { get; set; } public string qiniuyunSK { get; set; } public string qiniuyunBucket { get; set; } public string prefixPath { get; set; } }
配置信息:
"Qny": { "qiniuyunAK": "*",//ak "qiniuyunSK": "*",//sk "qiniuyunBucket": "**",存儲空間名稱 "prefixPath": "http://upload.qiniup.com"//七牛雲地址 }
讀取配置信息(在startup文件中的ConfigureServices添加):
services.Configure<QnySetting>(this.Configuration.GetSection("Qny"));
第三步:復制控制器及視圖代碼
視圖代碼:
<form method="post" action="/Upload/UploadQiniu" enctype="multipart/form-data"> <input name="file" type="file" /> <input type="submit" value="提交" /> </form>
控制器代碼:
private readonly QnySetting _Qny; public UploadController(IOptions<QnySetting> Qny) { _Qny = Qny.Value; } public IActionResult Index() { return View(); } [HttpPost] public List<Object> UploadQiniu() { Mac mac = new Mac(_Qny.qiniuyunAK, _Qny.qiniuyunSK);// AK SK使用 PutPolicy putPolicy = new PutPolicy(); putPolicy.Scope = _Qny.qiniuyunBucket; string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());//token生成 IFormFileCollection files = Request.Form.Files; Config config = new Config() { Zone = Zone.ZONE_CN_East, UseHttps = true }; var res = Request.Form.ToArray(); FormUploader upload = new FormUploader(config); HttpResult result = new HttpResult(); List<Object> list = new List<Object>(); foreach (IFormFile file in files)//獲取多個文件列表集合 { if (file.Length > 0) { var _fileName = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim(‘"‘); var _qiniuName = _Qny.prefixPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + _fileName;//重命名文件加上時間戳 Stream stream = file.OpenReadStream(); result = upload.UploadStream(stream, _qiniuName, token, null); if (result.Code == 200) { list.Add(new { fileName = _fileName, qiniuName = _qiniuName, uploadTime = DateTime.Now}); } else { throw new Exception(result.RefText);//上傳失敗錯誤信息 } } } return list; }
第四部:然後運行上傳圖片,結果如圖所示
本文來自:https://www.cnblogs.com/OMango/p/8447480.html 其中優化了一下
.NET Core項目----七牛雲圖片上傳