Http MultipartFormDataContent

我被要求在C#中执行以下操作:

/** * 1. Create a MultipartPostMethod * 2. Construct the web URL to connect to the SDP Server * 3. Add the filename to be attached as a parameter to the MultipartPostMethod with parameter name "filename" * 4. Execute the MultipartPostMethod * 5. Receive and process the response as required * / 

我写了一些没有错误的代码,但是没有附加文件。

有人可以查看我的C#代码,看看我是否错误地编写了代码?

这是我的代码:

 var client = new HttpClient(); const string weblinkUrl = "http://testserver.com/attach?"; var method = new MultipartFormDataContent(); const string fileName = "C:\file.txt"; var streamContent = new StreamContent(File.Open(fileName, FileMode.Open)); method.Add(streamContent, "filename"); var result = client.PostAsync(weblinkUrl, method); MessageBox.Show(result.Result.ToString()); 

在SO上已多次询问过这个问题。 这是一些可能的解决方案:

C#HttpClient 4.5 multipart / form-data上传: C#HttpClient 4.5 multipart / form-data上传

C#中的HttpClient Multipart Form Post :C#中的HttpClient Multipart Form Post

在个人注释中,检查请求中发送的post数据,并检查响应。 提琴手非常出色。

我知道这是一个老post但是对于那些寻求解决方案的人来说,提供一个更直接的答案,这就是我发现的:

 using System.Diagnostics; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; public class UploadController : ApiController { public async Task PostFormData() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { Trace.WriteLine(file.Headers.ContentDisposition.FileName); Trace.WriteLine("Server file path: " + file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } } 

这是我发现它的地方http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
有关更精细的实施
http://galratner.com/blogs/net/archive/2013/03/22/using-html-5-and-the-web-api-for-ajax-file-uploads-with-image-preview-and-一个正在进行中,bar.aspx

在C#中发布MultipartFormDataContent很简单,但第一次可能会令人困惑。 这是在发布.png .txt等时适合我的代码。

 // 2. Create the url string url = "http://sofzh.miximages.com/c%23/...; string filename = myFile.png"; // In my case this is the JSON that will be returned from the post string result = ""; // 1. Create a MultipartPostMethod // "NKdKd9Yk" is the boundary parameter using (var formContent = new MultipartFormDataContent("NKdKd9Yk")) { content.Headers.ContentType.MediaType = "multipart/form-data"; // 3. Add the filename C:\\... + fileName is the path your file Stream fileStream = System.IO.File.OpenRead("C:\\Users\\username\\Pictures\\" + fileName); content.Add(new StreamContent(fileStream), fileName, fileName); using (var client = new HttpClient()) { // Bearer Token header if needed client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _bearerToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data")); try { // 4.. Execute the MultipartPostMethod var message = await client.PostAsync(url, formContent); // 5.a Receive the response result = await message.Content.ReadAsStringAsync(); } catch (Exception ex) { // Do what you want if it fails. throw ex; } } } // 5.b Process the reponse Get a usable object from the JSON that is returned MyObject myObject = JsonConvert.DeserializeObject(result); 

在我的情况下,我需要在发布后对对象做一些事情,所以我用JsonConvert将它转换为该对象。

我调试了这个问题在这里:

 method.Add(streamContent, "filename"); 

这个’添加’实际上并没有将文件放在Multipart Content的BODY中。