ASP.NET Core 簡單實現七牛圖片上傳(FormData 和 Base64)

來源:互聯網
上載者:User

標籤:private   stream   public   圖片   

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和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 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 = {};        //產生base64        var 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>


ASP.NET Core 簡單實現七牛圖片上傳(FormData 和 Base64)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.