gpt4 book ai didi

c# - Http MultipartFormDataContent

转载 作者:可可西里 更新时间:2023-11-01 07:47:07 27 4
gpt4 key购买 nike

有人要求我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com