1

I'm getting this error when trying to upload a file to 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 Code

[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;
}

the error happens at

var pf = (System.Web.HttpPostedFile)f;

the f object is a string with value 'file'... WHY?!?! any help would be appreciated.

5
  • What is the value of f when the error is thrown? Commented Dec 2, 2019 at 20:39
  • type string = "file" Commented Dec 2, 2019 at 20:40
  • So you are trying to convert the value"file" to an instance of System.Web.HttpPostedFile? Commented Dec 2, 2019 at 20:41
  • yes, but why is it string and not System.Web.HttpPostedFile Commented Dec 2, 2019 at 20:41
  • @boruchsiper see my answer; you're looping over the list of keys in the HttpFileCollection, not the actual files that the entries point to within the collection Commented Dec 2, 2019 at 20:46

1 Answer 1

4

Because when you enumerate over HttpRequest.PostedFiles you're enumerating over its keys (the names, which are all 'file' based on your JS), not the files:

        foreach (var key in httpRequest.Files)
        {
            var pf = httpRequest.Files[key]; // implicit cast to HttpPostedFile

            pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
        }


EDIT TO ADD:

With that said, you'll need to update your JS to use unique names in FormData or else you'll only be able to read one file out of your HttpContext's HttpFileCollection:

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

    }

See HttpFileCollection on MSDN

Sign up to request clarification or add additional context in comments.

1 Comment

@CaseyCrookston it was actually your comment that gave me the hunch. Then I remembered dealing with a similar issue on my own file uploading implementation in .NET

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.