ess*_*kar 20 c# file-upload .net-4.5 dotnet-httpclient
我正在尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)
这只发送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;
}
Run Code Online (Sandbox Code Playgroud)
这在线鲨上看起来是正确的.但我没有在控制器中看到这些文件.
[HttpPost]
public ActionResult UploadProfileImage(IEnumerable<HttpPostedFileBase> postedFiles)
{
if(postedFiles == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
// more code here
}
Run Code Online (Sandbox Code Playgroud)
postedFiles仍然是空的.有任何想法吗?
ess*_*kar 29
搞定了.但行为很奇怪.
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16376 次 |
| 最近记录: |