MultiPartFormDataContent

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());

最佳答案

在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/

10-11 00:57