ASP.NET Core Web API接收文件传输

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.  
    }

可以将文件直接拷贝到其他文件,或者获取文件内容解析校验。

原文地址:https://www.cnblogs.com/bruce1992/p/14053338.html