HttpClient的:如何上传多个文件一次 [英] HttpClient: How to upload multiple files at once
本文介绍了HttpClient的:如何上传多个文件一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要上传使用muliple文件 System.Net.Http.HttpClient 。
I am trying to upload muliple files using 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的,但是我预期的多部分/混合的地方。在后
this only sends mulipart/form-data, but i expected multipart/mixed somewhere in the post.
更新:好吧,我得到了周围
UPDATE: Ok, i got around.
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;
}
这看起来线鲨鱼正确的。但我不认为在我的控制器中的文件
This looks correct on wire shark. but i do not see the files in my controller.
[HttpPost]
public ActionResult UploadProfileImage(IEnumerable<HttpPostedFileBase> postedFiles)
{
if(postedFiles == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
// more code here
}
postedFiles
仍是空。任何想法?
推荐答案
钉它。但是行为很奇怪。
Nailed it. But behaviour is strange.
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
}
这篇关于HttpClient的:如何上传多个文件一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文