前端使用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); }