通过axios将文件上传到WebApi

问题描述 投票:1回答:1

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

javascript c# asp.net-web-api axios
1个回答
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); }

© www.soinside.com 2019 - 2024. All rights reserved.