【问题标题】:Uploading files via axios to WebApi通过 axios 上传文件到 WebApi
【发布时间】: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


【解决方案1】:

因为当您枚举 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 中的唯一名称,否则您将只能从您的 HttpContextHttpFileCollection 中读取一个文件:

    for (var i = 0; i < e.target.files.length; i++) {
        formData.append('file' + i, e.target.files[i]);

    }

HttpFileCollection on MSDN

【讨论】:

  • @CaseyCrookston 实际上是你的评论给了我预感。然后我记得在 .NET 中处理我自己的文件上传实现的类似问题
猜你喜欢
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2021-04-18
  • 2020-10-05
  • 1970-01-01
相关资源
最近更新 更多