【问题标题】:Http MultipartFormDataContentHttp MultipartFormDataContent
【发布时间】:2013-12-17 15:57:06
【问题描述】:

我被要求在 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());

【问题讨论】:

标签: c# post httpclient filestream multipartform-data


【解决方案1】:

我知道这是一篇旧帖子但是对于那些寻找解决方案的人来说,为了提供更直接的答案,这是我发现的:

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<HttpResponseMessage> 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-a-progress-bar.aspx

【讨论】:

  • 这个读取 multipart/form-data,它不发送它。我想知道您是否阅读了这个甚至不涉及 ASP.NET Web API 的问题
  • 这是服务器端代码。 OP 要求提供发送请求的客户端代码。
  • @SOusedtobegood 我知道这条评论很旧,但我有一段时间没有登录了。嗯,问题是 C#,所以隐含了 .NET,并且代码不是来自 ASP,而是来自我正在处理的 MVC 项目。 O_o
  • @MostafaZeinali 老兄,你什么时候见过 C# 客户端?在发布 cmets 之前,您真的必须阅读这些问题。问题清楚地指出“有人可以看看我的 C# 代码,看看我是否写错了代码?”。 o_O
  • @iuppiter 我的朋友多次看到 C# 客户端。任何想要向/从服务器发送/接收数据的客户端 C# 应用程序都需要编写客户端代码。我在这里又看到了一次,在作者的问题中,在这一行:“client.PostAsync(weblinkUrl, method);”这是一个客户端代码,它试图向服务器发送一个发布请求。干净利落。另一方面,您的代码是服务器端代码,它接收多部分发布请求并从中“读取”附加文件。你和作者可以一起做一个网络应用,你做服务器端,他做客户端。
【解决方案2】:

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

method.Add(streamContent, "filename");

此“添加”实际上并未将文件放入多部分内容的正文中。

【讨论】:

    【解决方案3】:

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

    // 2. Create the url 
    string url = "https://myurl.com/api/...";
    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"))
    {
        formContent.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);
        formContent.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<MyObject>(result);
    

    在我的情况下,我需要在对象发布后对其进行处理,因此我使用 JsonConvert 将其转换为该对象。

    【讨论】:

    • 什么是content?同formContent?
    • @dube 是的,当我写答案时,我滑倒并放置了内容而不是 formContent。我纠正了它。感谢您指出这一点
    猜你喜欢
    • 2015-08-27
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多