【发布时间】:2020-03-27 12:00:41
【问题描述】:
我在尝试将文件上传到 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' 的字符串...为什么?!?!
任何帮助将不胜感激。
【问题讨论】:
-
抛出错误时
f的值是多少? -
type string = "file"
-
所以您正试图将值
"file"转换为System.Web.HttpPostedFile的实例? -
是的,但为什么是字符串而不是 System.Web.HttpPostedFile
-
@boruchsiper 看到我的回答;您正在循环遍历
HttpFileCollection中的键列表,而不是条目在集合中指向的实际文件
标签: javascript c# asp.net-web-api axios