1、Net Core創建api接口,用於接收外部請求,進行文件的上傳
2、添加控制器類,添加如下代碼:
[HttpPost] [Route("PostFile")] public String PostFile([FromForm] IFormCollection formCollection) { String result = "Fail"; if (formCollection.ContainsKey("user")) { var user = formCollection["user"]; } FormFileCollection fileCollection = (FormFileCollection)formCollection.Files; foreach (IFormFile file in fileCollection) { StreamReader reader = new StreamReader(file.OpenReadStream()); String content = reader.ReadToEnd(); String name = file.FileName; String filename = @"D:/Test/" + name; if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } using (FileStream fs = System.IO.File.Create(filename)) { // 復制文件 file.CopyTo(fs); // 清空緩沖區數據 fs.Flush(); } result = "Success"; } return result; }
3、修改其中需要注意的點,如文件夾是否存在未做判斷,需要提前創建文件夾或添加文件夾判斷
4、通過postman進行接口測試,form-data數據請求方式,key選擇File,value選擇文件,進行提交(如圖)。
5、注意問題:提交請求之后,如遇到報錯返回代碼413,通常是文件請求大小被限制。目前可提供以下幾種解決方案,但在不同條件下生效的方式不一樣,需要一一測試
方法一:在接口方法上添加特性[DisableRequestSizeLimit]
同時在startup.cs中的添加
services.Configure<FormOptions>(x => { x.MultipartBodyLengthLimit = 209_715_200;//最大200M });
方法二:在startup.cs中的添加
ervices.Configure<FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.MultipartBodyLengthLimit = int.MaxValue; x.MemoryBufferThreshold = int.MaxValue; });
如果后續有其它問題或解決方案,將在評論區進行補充。