通过axios将文件上传到WebApi

时间:2019-12-02 20:33:51

标签: javascript c# asp.net-web-api axios

尝试将文件上传到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'...的字符串...为什么?!?! 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

因为枚举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的{​​{1 }}:

HttpFileCollection

请参见HttpFileCollection on MSDN