gpt4 book ai didi

c# - HttpClient : How to upload multiple files at once

转载 作者:IT王子 更新时间:2023-10-29 04:38:37 33 4
gpt4 key购买 nike

我正在尝试使用 System.Net.Http.HttpClient 上传多个文件.

using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(imageStream), "image", "image.jpg");
content.Add(new StreamContent(signatureStream), "signature", "image.jpg.sig");

var response = await httpClient.PostAsync(_profileImageUploadUri, content);
response.EnsureSuccessStatusCode();
}

这只发送 mulipart/form-data,但我希望 multipart/mixed 出现在帖子的某处。

更新:好的,我解决了。

using (var content = new MultipartFormDataContent())
{
var mixed = new MultipartContent("mixed")
{
CreateFileContent(imageStream, "image.jpg", "image/jpeg"),
CreateFileContent(signatureStream, "image.jpg.sig", "application/octet-stream")
};

content.Add(mixed, "files");

var response = await httpClient.PostAsync(_profileImageUploadUri, content);
response.EnsureSuccessStatusCode();
}

private StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("file") {FileName = fileName};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}

这在 wire shark 上看起来是正确的。但我没有在我的 Controller 中看到这些文件。

[HttpPost]
public ActionResult UploadProfileImage(IEnumerable<HttpPostedFileBase> postedFiles)
{
if(postedFiles == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

// more code here
}

postedFiles 仍然为空。有什么想法吗?

最佳答案

搞定了。但是行为很奇怪。

using (var content = new MultipartFormDataContent())
{
content.Add(CreateFileContent(imageStream, "image.jpg", "image/jpeg"));
content.Add(CreateFileContent(signatureStream, "image.jpg.sig", "application/octet-stream"));

var response = await httpClient.PostAsync(_profileImageUploadUri, content);
response.EnsureSuccessStatusCode();
}

private StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
}; // the extra quotes are key here
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}

[HttpPost]
public ActionResult UploadProfileImage(IList<HttpPostedFileBase> files)
{
if(files == null || files.Count != 2)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

// more code
}

关于c# - HttpClient : How to upload multiple files at once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16906711/

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