HttpClient:如何一次上传多个文件
本文关键字:文件 何一次 HttpClient | 更新日期: 2023-09-27 18:16:43
我正在尝试使用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();
}
这只发送多部分/表单数据,但我期望在帖子的某个地方多部分/混合。
更新:好吧,我得到了。
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是正确的。但是我没有看到我的控制器中的文件。
[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
}