尝试将文件上传到webapi时出现此错误
无法将类型为“ System.String”的对象转换为类型为“ System.Web.HttpPostedFile”的对象
javascript:
UploadReceivingIssueImages(e) {
if (!e.target.files || e.target.files.length === 0)
return;
let formData = new FormData();
for (var i = 0; i < e.target.files.length; i++) {
formData.append('file', e.target.files[i]);
}
var vm = this;
axios.post('../api/receiving/UploadDocReceivingIssueImages?headerId=' + this.SelectedSubIdIdObj.HeaderId,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
vm.getDocReceivingIssueImages();
console.log('SUCCESS!!');
}, function (er) {
alert("Couldn't upload images")
});
}
WebApi代码
[HttpPost]
public bool UploadDocReceivingIssueImages([FromUri] int headerId)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count < 1)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("No File Uploaded"),
ReasonPhrase = "No File Uploaded"
};
throw new HttpResponseException(resp);
}
var dirPath = @"\\dirPath";
foreach (var f in httpRequest.Files)
{
var pf = (System.Web.HttpPostedFile)f;
pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
}
return true;
}
错误发生在
var pf = (System.Web.HttpPostedFile)f;
该f
对象是一个值为'file'的字符串...为什么?!?!任何帮助,将不胜感激。
因为当您枚举HttpRequest.PostedFiles时,您枚举的是其键(名称,它们都是基于JS的“文件”),而不是文件:
foreach (var key in httpRequest.Files)
{
var pf = httpRequest.Files[key]; // implicit cast to HttpPostedFile
pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
}
编辑添加:
随着中说,你需要更新你的JS使用的唯一的名称FormData
,否则你就只能读取一个文件出你HttpContext
的HttpFileCollection
:
for (var i = 0; i < e.target.files.length; i++) {
formData.append('file' + i, e.target.files[i]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句