2017-10-12 91 views
1

我有以下型號:上傳文件到網絡API

public class FileModel 
{ 
    public byte[] FileData{get;set;} 
    public string FileName {get;set;} 
} 

我已經編寫這我的Web應用程序消耗私有的Web API服務。 當用戶上傳文件時,我將這些文件轉換爲字節數組,並從C#代碼(不是從HTML頁面發送List<FileModel>到我的Web API,因爲我的Web API從我的網站是私人的),這將保存我的文件和返回結果。

的Web API方法:

[HttpPost] 
public UploadFiles(List<FileModel> files) 
{ 
// Do work 
} 

上面的代碼休息,如果我上傳許多大型文件 - 代碼的失敗,因爲它們超出了最大長度序列化序列化大文件FileModel秒。

如何解決此問題?有沒有其他方法可以將文件上傳到Web API而不會將其暴露給用戶?

+0

的可能的複製[如何上傳與進度ASP.NET MVC4網絡API一個大文件(https://stackoverflow.com/questions/15506648/how-to-upload-a-large-file -with-asp-net-mvc4-web-api-with-progressbar) – Liam

+0

使用塊字節方法異步上傳。 https://stackoverflow.com/questions/583970/need-loop-to-copy-chunks-from-byte-array –

+0

@NikhilKS我不想做多個網絡API調用。 –

回答

0

將此項添加到您的web.config文件中。

<configuration> 
    <system.web> 
     <httpRuntime maxRequestLength ="1999999"/> 
</system.web> 
</configuration> 

,並增加在MVC config文件內容的長度。

<system.webServer> 
    <security> 
     <requestFiltering> 
     <requestLimits maxAllowedContentLength="1999999999" /> 
     </requestFiltering> 
    </security> 
<system.webServer> 

maxRequestLength值以千字節爲單位。

maxAllowedContentLength值以字節爲單位。

您可以根據您的要求改變上述尺寸。

+0

感謝但maxRequestLength不是我的問題的原因。 –

+0

當我使用httpClient.PostAsJsonAsync <列表>(「API URL」,postObj)。我返回未找到Web API方法的響應。 –

+0

但這僅僅適用於大文件 –

0

這是針對這種情況的一些解決方案。

您的控制器操作不會接受任何參數,如代碼段所示。

public async Task<HttpResponseMessage> PostByteArrayAsync() 
{ 
     string root = HttpContext.Current.Server.MapPath("~/folder"); 
     var provider = new MultipartFormDataStreamProvider(root); 
     await Request.Content.ReadAsMultipartAsync(provider); 
     foreach (var file in provider.FileData) 
     { 
      var buffer = File.ReadAllBytes(file.LocalFileName); 
      // store to db and other stuff 
     } 
     return Ok(); 
} 

以上代碼爲前端樣本。

UploadData(event) { 
     this.setState({ loading: true }); 
     event.preventDefault(); 
     let data = new FormData(); 
     let fileData = document.querySelector('input[type="file"]').files[0]; 
     data.append("data", fileData); 
     let that = this; 
     fetch("api/upload", { 
      method: "POST", 
      "Content-Type": "multipart/form-data", 
      "Accept": "application/json", 
      body: data 
     }).then(function (res) { 
      if (res.ok) { 
       call('api', 'GET').then(response => { response.error ? response.message : that.props.change(response); that.setState({ loading: false }) }); 
      } 
      else { 
       that.setState({ loading: false }); 
       that.failedMsg(); 
      } 
     }) 
    } 
+0

嗨感謝您的響應,但我沒有嘗試將文件發送到我的Web API直接。我發佈文件到我的MVC操作控制器,並使我的控​​制器操作POST文件到我的Web API。我不希望我的Web API網址因爲它的私有(即,特定於我的網站) –