1. 程式人生 > >AspNetCore 檔案上傳(模型繫結、Ajax) 兩種方式 get到了嗎?

AspNetCore 檔案上傳(模型繫結、Ajax) 兩種方式 get到了嗎?

就目前來說,ASP.NET Core2.1了,已經相當成熟了,希望下個專案爭取使用吧!!

上傳檔案的三種方式("我會的,說不定還有其他方式")

模型繫結

Ajax

WebUploader

一。模型繫結

  官方機器翻譯的地址:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads,吐槽一下,這翻譯的啥玩膩啊。。。

<form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave">
        <div>
            <div>
                <p>Form表單多個上傳檔案:</p>
                <input type="file" name="files" multiple />
                <input type="submit" value="上傳" />
            </div>
        </div>
    </form>

  其中,asp-controller和asp-action,(這個是TagHelper的玩法)是我們要訪問的控制器和方法,不懂taghelper的可以看一下我關於aspnetcore的taghelper的相關文章

  給我們的input標籤加上 multiple 屬性,來支援多檔案上傳.

建立一個控制器,我們編寫上傳方法如下:

public async Task<IActionResult> FileSave(List<IFormFile> files)

        {
            var files = Request.Form.Files;
            
long size = files.Sum(f => f.Length); string webRootPath = _hostingEnvironment.WebRootPath; string contentRootPath = _hostingEnvironment.ContentRootPath; foreach (var formFile in files) { if (formFile.Length > 0) {
string fileExt = GetFileExt(formFile.FileName); //副檔名,不含“.” long fileSize = formFile.Length; //獲得檔案大小,以位元組為單位 string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //隨機生成新的檔名 var filePath = webRootPath +"/upload/" + newFileName; using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } } } return Ok(new { count = files.Count, size }); }
View Code

這裡我們採用Asp.NET Core的新介面IFormFile,  IFormFile的具體定義如下:

public interface IFormFile

{

    string ContentType { get; }
    string ContentDisposition { get; }
    IHeaderDictionary Headers { get; }
    long Length { get; }
    string Name { get; }
    string FileName { get; }
    Stream OpenReadStream();
    void CopyTo(Stream target);
    Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}

  上面的程式碼使用了IHostingEnvironment來獲取專案的根目錄地址.

建構函式注入的程式碼如下:

        private readonly IHostingEnvironment _hostingEnvironment;
        public UpLoadFileController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

  二。ajax上傳

前臺程式碼:

function doUpload() {

        var formData = new FormData($("#uploadForm")[0]);
        $.ajax({
            url: '@Url.Action("FileSave")',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                alert(returndata);
            },

            error: function (returndata) {
                alert(returndata);
            }
        });
        }

  後臺程式碼和模型繫結有點區別,不要寫引數的了,獲取直接reques裡面的了

public async Task<IActionResult> FileSave()
{
            var date = Request;
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            string webRootPath = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    string fileExt = GetFileExt(formFile.FileName); //副檔名,不含“.”
                    long fileSize = formFile.Length; //獲得檔案大小,以位元組為單位

                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //隨機生成新的檔名
                    var filePath = webRootPath +"/upload/" + newFileName;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }
            return Ok(new { count = files.Count, size });
 }

  改為直接從Request.Form.Files中獲取檔案集合.