ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ASP.NET Core 簡單實現七牛圖片上傳(FormData 和 Base64)
七牛圖片上傳 SDK(.NET 版本):https://developer.qiniu.com/kodo/sdk/1237/csharp
UpoladService示例代碼:
public class UpoladService : IUpoladService {private readonly static string[] _imageExtensions = new string[] { ".jpg", ".png", ".gif", ".jpeg", ".bmp" };private AppSettings _appSettings;public UpoladService(IOptions<AppSettings> appSettings){_appSettings = appSettings.Value;}public async Task<SubmitResult> UploadStream(Stream stream, string fileName, AppType appType){if (stream == null){return SubmitResult.Fail("圖片為null");}if (string.IsNullOrWhiteSpace(fileName)){return SubmitResult.Fail("圖片名稱為空");}try{var extensionName = fileName.Substring(fileName.LastIndexOf("."));if (!_imageExtensions.Contains(extensionName.ToLower())){return SubmitResult.Fail("圖片格式有誤");}var generateFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff-")}{Guid.NewGuid().GetHashCode().ToString().Replace("-", string.Empty)}{extensionName}";var saveKey = $"wl/{appType.ToString().ToLower()}/{generateFileName}";// 生成(上傳)憑證時需要使用此Mac// 這個示例單獨使用了一個Settings類,其中包含AccessKey和SecretKey// 實際應用中,請自行設置您的AccessKey和SecretKeyMac mac = new Mac(_appSettings.AccessKey, _appSettings.SecretKey);// 上傳策略,參見 // https://developer.qiniu.com/kodo/manual/put-policyPutPolicy putPolicy = new PutPolicy();// 如果需要設置為"覆蓋"上傳(如果云端已有同名文件則覆蓋),請使用 SCOPE = "BUCKET:KEY"// putPolicy.Scope = bucket + ":" + saveKey;putPolicy.Scope = _appSettings.Bucket;// 上傳策略有效期(對應于生成的憑證的有效期) putPolicy.SetExpires(3600);// 上傳到云端多少天后自動刪除該文件,如果不設置(即保持默認默認)則不刪除//putPolicy.DeleteAfterDays = 1;// 生成上傳憑證,參見// https://developer.qiniu.com/kodo/manual/upload-token string jstr = putPolicy.ToJsonString();string token = Auth.CreateUploadToken(mac, jstr);FormUploader fu = new FormUploader();var result = await fu.UploadStreamAsync(stream, saveKey, token);if (result.Code == 200){return SubmitResult.Success($"{_appSettings.Domain}/{saveKey}");}return SubmitResult.Fail("上傳失敗");}catch (Exception ex){return SubmitResult.Fail($"上傳失敗:{ex.Message}");}} }UploadController示例代碼:
[EnableCors("default")] [Route("upload")] public class UploadController : WebApiController {private IUpoladService _upoladService;public UploadController(IUpoladService upoladService){_upoladService = upoladService;}[Route("{appType}/stream")][HttpPost]public async Task<IActionResult> UploadByStream(AppType appType){if (Request.Form.Files.Count == 0){return Fail("圖片不存在");}var file = Request.Form.Files[0];var result = await _upoladService.UploadStream(file.OpenReadStream(), file.FileName, appType);if (result.IsSuccess){return Ok(new { pic_url = result.Data, is_success = true });}return Fail(result.Message);}[Route("{appType}/base64")][HttpPost]public async Task<IActionResult> UploadByBase64([FromBody]JObject data, AppType appType){var imageBase64 = data["image_base64"].ToObject<string>();var fileName = data["file_name"].ToObject<string>();if (!string.IsNullOrWhiteSpace(imageBase64)){var reg = new Regex("data:image/(.*);base64,");imageBase64 = reg.Replace(imageBase64, "");byte[] imageByte = Convert.FromBase64String(imageBase64);var stream = new MemoryStream(imageByte);var result = await _upoladService.UploadStream(stream, fileName, appType);if (result.IsSuccess){return Ok(new { pic_url = result.Data, is_success = true });}return Fail(result.Message);}return Json(new { success = false, result = "請選擇文件!" });} }JS 上傳圖片示例代碼:
<form method="post" enctype="multipart/form-data"><input type="file" id="files"name="files" multiple /><input type="button"id="uploadStream"value="Upload Selected Files" /><input type="button"id="uploadBase64"value="Upload Selected Files" /> </form><script> $(document).ready(function () {$("#upload").click(function (evt) {var fileUpload = $("#files").get(0);var files = fileUpload.files;var data = new FormData();for (var i = 0; i < files.length; i++) {data.append(files[i].name, files[i]);}$.ajax({type: "POST",url: "http://localhost:5002/upload/avatar/stream",processData: false,contentType: false,data: data,success: function (data) {if (data.is_success) {console.log(data.pic);}else {console.log(data.msg);}console.log(data);},error: function () {console.log("There was error uploading files!");}});});$("#uploadBase64").click(function (evt) {var fileUpload = $("#files").get(0);var files = fileUpload.files;var data = {};//生成base64var reader = new FileReader();reader.readAsDataURL(files[0]);reader.onload = function () {data.image_base64 = reader.result;data.file_name = files[0].name;$.ajax({type: "POST",url: "http://localhost:5002/upload/avatar/base64",contentType: 'application/json; charset=utf-8',data: JSON.stringify(data),dataType: 'json',success: function (data) {if (data.is_success) {console.log(data.pic);}else {console.log(data.msg);}console.log(data);},error: function () {console.log("There was error uploading files!");}});return reader.result;};reader.onerror = function (error) {console.log('Error: ', error);};}); }); </script>轉載于:https://www.cnblogs.com/xishuai/p/asp-net-core-upload-image-with-qiniu.html
總結
以上是生活随笔為你收集整理的ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NYOJ--517--最小公倍数(大数打
- 下一篇: 二叉查找树BST----java实现