c# - Http MultipartFormDataContent

标签 c# post httpclient filestream multipartform-data

有人要求我在 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# 中发布 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 将其转换为该对象。

关于c# - Http MultipartFormDataContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319886/

相关文章:

c# - 开源代码片段存储库

javascript - 401 使用 POST 方法 API 身份验证失败

java - 使用java点击knoxrest服务?

java - HttpClient 4.1.1 在使用 NTLM 进行身份验证时返回 401,浏览器工作正常

c# - IVMRWindowlessControl9 未呈现到父 WPF 窗口中

c# - wix - 安装前删除旧的程序文件夹

jquery - 使用 Jquery AJAX 从 ASP.NET Web 服务器获取对象

httpclient - 哪个版本的 apache http 客户端与 java 1.4.2 兼容?

c# - 在 ASP.NET 5 和 MVC 6 中将启动配置与 Web 项目分离的最佳方法

json - 服务器可以通过 POST 发送带有 EventSource 传递参数的事件 (SSE)