.NET Core Web APi FormData多文件上传,IFormFile强类型文件灵活绑定
前端使用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); }
上传后文件: