.NET Core Web APi FormData多檔案上傳,IFormFile強型別檔案靈活繫結
阿新 • • 發佈:2020-08-14
前端使用FormData進行實現批量上傳
<!doctype html> <html> <head> <meta charset="utf-8"> <title>上傳</title> </head> <form method="post" id="uploadForm" enctype="multipart/form-data"> <input type="file" name="file" multiple /> <input type="button" value="上傳" onclick="doUpload()" /> </form> <body> <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> $(function () { }); function doUpload() { var formData = new FormData($("#uploadForm")[0]); $.ajax({ url:'http://localhost:5000/api/Path/Upload', type: 'post', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { console.dir(returndata); }, error: function (returndata) { console.dir(returndata); } }) }</script>
批量上傳選擇多個檔案:
後端.Net Core 使用 IFormFile 強型別靈活繫結獲取檔案資訊
/// <summary> /// 檔案上傳 /// </summary> /// <returns></returns> [HttpPost] public MethodResult Upload([FromForm(Name = "file")] List<IFormFile> files) { files.ForEach(file => { var fileName = file.FileName; string fileExtension = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);//獲取檔名稱字尾 //儲存檔案 var stream = file.OpenReadStream(); // 把 Stream 轉換成 byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 設定當前流的位置為流的開始 stream.Seek(0, SeekOrigin.Begin); // 把 byte[] 寫入檔案 FileStream fs = new FileStream("D:\\" + file.FileName, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); }); return new MethodResult("success", 1); }
上傳後文件: