c# .net6 使用multipart/form-data POST上传文件,参数有sp1和sp2,给出范例
时间: 2024-12-13 10:22:54 浏览: 6
在C# .NET 6 中,如果你需要使用`multipart/form-data`格式POST上传文件并附带额外的数据(如sp1和sp2),你可以使用HttpClient或者第三方库如Microsoft.AspNetCore.Http.Client。下面是一个基本的示例,展示如何通过HttpClient发送这样的请求:
```csharp
using System.Net.Http;
using System.IO;
using System.Text;
public async Task UploadFileWithFormDataAsync(string url, string sp1, string sp2, Stream fileStream)
{
// 创建一个HttpClient实例
var client = new HttpClient();
// 创建MultipartContent对象作为主体
var content = new MultipartFormDataContent();
// 添加文本参数
var formContent = new StringContent($"sp1={sp1}&sp2={sp2}", Encoding.UTF8, "application/x-www-form-urlencoded");
content.Add(formContent);
// 添加文件参数
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file", // 文件名字段
FileName = Path.GetFileName(fileStream.Name) // 获取流对应的文件名
};
content.Add(fileContent);
try
{
// 发送POST请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Upload successful with status {response.StatusCode}");
}
else
{
Console.WriteLine($"Upload failed with status {response.StatusCode} and reason {response.ReasonPhrase}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred during upload: {ex.Message}");
}
}
// 调用函数时提供文件流、sp1和sp2值
string filePath = "path_to_your_file";
FileStream fileStream = File.OpenRead(filePath);
string sp1 = "value1";
string sp2 = "value2";
await UploadFileWithFormDataAsync("http://your-api-url.com/upload", sp1, sp2, fileStream);
```
阅读全文