我正在尝试使用 Html2 输入 type="file" 和 angular2 http.post 请求上传文件。当请求到达 Web api 时,它会在
中失败Request.Content.IsMimeMultipartContent()
使用 Postman 提交请求时,它不会失败(当我不在标头中包含 Content-Type 时,因为邮递员会处理它)。
查看我的代码: 网页:
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx,.dwg,.jpeg,.jpg">
服务功能:
uploadFile(event) {
let fileUploadUrl = this.webApiFileUploadURL;
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this._http.post(`${this.webApiFileUploadURL}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
WebApi post 请求(失败于 if(!Request.Content.IsMimeMultipartContent())):
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent()) // Fails here
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
经过彻底的研究 - 我成功了:
发帖时无需设置content-type header属性。
我已将其从我的 angular2 http.post 请求中删除,并且
传递的web-api post方法中的Request.Content.IsMimeMultipartContent()(与postman中相同)
如果其他人遇到此问题“此资源不支持请求实体的媒体类型‘multipart/form-data’。”
您可能需要在 webapiconfig 中添加此内容
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
经过这么多阅读,我的猜测是您需要异步保存上传的文件(我将其称为 JQUERY_D_UPLOAD)。 我在下面创建了这个小型 ASP.NET C# 异步任务来帮助您入门。
public async Task<string> SaveFile()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
using (var stream = new FileStream(Path.Combine("~/uploads", Guid.NewGuid().ToString() + Path.GetExtension(file.FileName)), FileMode.Create, FileAccess.Write, FileShare.Write, 4096, useAsync: true))
{
await file.InputStream.CopyToAsync(stream);
}
}
}