ASP.NETCoreWebAPI接收文件传输
ASP.NET解析API参数的⽅式有很多种,包括[FromBody],[FromForm],[FromServices],[FromHeader][FromQuery].⽂件传输⽅式也分很多种,包括
1) 前端读取⽂件内容,将内容以text/xml/json/binary等形式传输。2)前端不做任何处理,将⽂件放到Form中传输。
此处对Form传输⽂件进⾏介绍,可以将form看作是个多功能的词典类型,value值可以是text,也可以是FormFile.1.
[HttpPost]2.
[Route(\"PostFile\")]3.
public String PostFile([FromForm] IFormCollection formCollection)4. {5.
String result = \"Fail\";6.
if (formCollection.ContainsKey(\"user\"))7. {8.
var user = formCollection[\"user\"];9. }10.
FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;11.
foreach (IFormFile file in fileCollection)12.
{13.
StreamReader reader = new StreamReader(file.OpenReadStream());14.
String content = reader.ReadToEnd();15.
String name = file.FileName;16.
String filename = @\"D:/Test/\" + name;17.
if (System.IO.File.Exists(filename))18.
{19.
System.IO.File.Delete(filename);20.
}21.
using (FileStream fs = System.IO.File.Create(filename))22.
{23.
// 复制⽂件24.
file.CopyTo(fs);25.
// 清空缓冲区数据26.
fs.Flush();27.
}
28.
result = \"Success\";29.
}30.
return result;31.
}
可以将⽂件直接拷贝到其他⽂件,或者获取⽂件内容解析校验。
因篇幅问题不能全部显示,请点此查看更多更全内容