2017-03-06 27 views
2

我正在嘗試編寫代碼以通過WinForm應用程序將文件上傳到WebApi。通過ASP.NET MVC上傳文件的客戶端代碼WebApi

的代碼的WebAPI就像是:

[HttpPost] 
[Route("UploadEnvelope")] 
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 
public Task<HttpResponseMessage> PostUploadEnvelope() 
{ 
    HttpRequestMessage request = this.Request; 
    if (!request.Content.IsMimeMultipartContent()) 
    { 
     throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 

    string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); 
    var provider = new MultipartFormDataStreamProvider(root); 

    var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(o => 
     { 
      foreach (MultipartFileData fileData in provider.FileData) 
      { 
       if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) 
       { 
        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"); 
       } 
       string fileName = fileData.Headers.ContentDisposition.FileName; 
       if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) 
       { 
        fileName = fileName.Trim('"'); 
       } 
       if (fileName.Contains(@"/") || fileName.Contains(@"\")) 
       { 
        fileName = Path.GetFileName(fileName); 
       } 
       File.Move(fileData.LocalFileName, Path.Combine(root, fileName)); 
      } 

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

但我不知道如何稱呼它,並在客戶端應用程序傳遞文件。

static string UploadEnvelope(string filePath, string token, string url) 
{ 
    using (var client = new HttpClient()) 
    { 
     client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); 


     // How to pass file here ??? 

     var response = client.GetAsync(url + "/api/Envelope/UploadEnvelope").Result; 

     return response.Content.ReadAsStringAsync().Result; 
    } 
} 

歡迎任何幫助或建議。提前致謝!

回答

1

首先您使用的是用於閱讀的Get方法。您必須改用Post

嘗試以下操作:

public static string UploadEnvelope(string filePath,string token, string url) 
{ 
    using (var client = new HttpClient()) 
    { 
     client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); 
     using (var content = new MultipartFormDataContent("Envelope" + DateTime.Now.ToString(CultureInfo.InvariantCulture))) 
     { 
      content.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(filePath))), "filename", "filename.ext"); 
      using (var message = await client.PostAsync(url + "/api/Envelope/UploadEnvelope", content)) 
      { 
       var input = await message.Content.ReadAsStringAsync(); 
       return "success"; 
      } 
     } 
    } 
} 

注意:對於大文件,你必須更改IIS web.config配置。

+0

很好的答案!上帝祝福你! –

+0

你能看到這個嗎? https://stackoverflow.com/questions/48278333/php-curl-to-net-httprequest-files-uploading-to-server –