2014-03-04 75 views
6

我想知道如何將zip文件發送到WebApi控制器,反之亦然。 問題是我的WebApi使用json傳輸數據。壓縮文件不可序列化,或者是流。一個字符串是可序列化的。但是,除了將zip轉換爲字符串併發送字符串之外,還必須有其他解決方案。這聽起來錯了。如何將zip文件發送到ASP.NET WebApi

任何想法如何做到這一點?

+3

如果您需要使用二進制文件,爲什麼要限制自己只允許使用JSON? WebApi支持通過多部分或原始字節流讀取二進制文件的多種方式。 –

回答

4

如果你的API方法需要一個HttpRequestMessage那麼你就可以拉來自此的流:

public HttpResponseMessage Put(HttpRequestMessage request) 
{ 
    var stream = GetStreamFromUploadedFile(request); 

    // do something with the stream, then return something 
} 

private static Stream GetStreamFromUploadedFile(HttpRequestMessage request) 
{ 
    // Awaiting these tasks in the usual manner was deadlocking the thread for some reason. 
    // So for now we're invoking a Task and explicitly creating a new thread. 
    // See here: http://stackoverflow.com/q/15201255/328193 
    IEnumerable<HttpContent> parts = null; 
    Task.Factory 
     .StartNew(() => parts = request.Content.ReadAsMultipartAsync().Result.Contents, 
         CancellationToken.None, 
         TaskCreationOptions.LongRunning, 
         TaskScheduler.Default) 
     .Wait(); 

    Stream stream = null; 
    Task.Factory 
     .StartNew(() => stream = parts.First().ReadAsStreamAsync().Result, 
         CancellationToken.None, 
         TaskCreationOptions.LongRunning, 
         TaskScheduler.Default) 
     .Wait(); 
    return stream; 
} 

這適用於我pos使用enctype="multipart/form-data"創建HTTP表單。

+0

這解決了我的問題。謝謝! –

4

嘗試使用簡單HttpResponseMessage,具有StreamContent內搞定,下載文件

public HttpResponseMessage Get() 
{ 
    var path = @"C:\Temp\file.zip"; 
    var result = new HttpResponseMessage(HttpStatusCode.OK); 
    var stream = new FileStream(path, FileMode.Open); 
    result.Content = new StreamContent(stream); 
    result.Content.Headers.ContentType = 
     new MediaTypeHeaderValue("application/octet-stream"); 
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
          { 
           FileName = "file.zip" 
          }; 
    return result; 
} 

和POST,上傳文件

public Task<HttpResponseMessage> Post() 
{ 
    HttpRequestMessage request = this.Request; 
    if (!request.Content.IsMimeMultipartContent()) 
    { 
     throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 


    var provider = new MultipartFormDataStreamProvider("C:\Temp"); 

    var task = request.Content.ReadAsMultipartAsync(provider). 
     ContinueWith<HttpResponseMessage>(o => 
     { 

      string file1 = provider.BodyPartFileNames.First().Value; 
      // this is the file name on the server where the file was saved 

      return new HttpResponseMessage() 
      { 
       Content = new StringContent("File uploaded.") 
      }; 
     } 
    ); 
    return task; 
}