您好,登錄后才能下訂單哦!
ASP.NET Core 簡單實現七牛圖片上傳(FormData 和 Base64)
七牛圖片上傳 SDK(.NET 版本):https://developer.qiniu.com/kodo/sdk/1237/csharp
UpoladService
示例代碼:
public class UpoladService : IUpoladService { private readonly static string[] _p_w_picpathExtensions = 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 (!_p_w_picpathExtensions.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和SecretKey Mac mac = new Mac(_appSettings.AccessKey, _appSettings.SecretKey); // 上傳策略,參見 // https://developer.qiniu.com/kodo/manual/put-policy PutPolicy 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 p_w_picpathBase64 = data["p_w_picpath_base64"].ToObject<string>(); var fileName = data["file_name"].ToObject<string>(); if (!string.IsNullOrWhiteSpace(p_w_picpathBase64)) { var reg = new Regex("data:p_w_picpath/(.*);base64,"); p_w_picpathBase64 = reg.Replace(p_w_picpathBase64, ""); byte[] p_w_picpathByte = Convert.FromBase64String(p_w_picpathBase64); var stream = new MemoryStream(p_w_picpathByte); 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 = {}; //生成base64 var reader = new FileReader(); reader.readAsDataURL(files[0]); reader.onload = function () { data.p_w_picpath_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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。