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

可以將文件直接拷貝到其他文件,或者獲取文件內容解析校驗。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM