Skip to main content
 首页 » 编程设计

javascript之通过axios上传文件到WebApi

2024年02月25日76kevingrace

尝试将文件上传到 webapi 时出现此错误

Unable to cast object of type 'System.String' to type '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 的"file"),而不是文件:

        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]); 
 
    } 

参见 HttpFileCollection on MSDN