简体   繁体   中英

Posting files to WebApi2 using AngularJS - cannot get filename or headers

I am using AngularJS to allow someone to post a file to my web service which is using c# WebAPI 2.

  self.AddDocument = function() { var f = document.getElementById('documentFile').files[0]; var r = new FileReader(); r.onloadend = function(e) { var data = e.target.result; console.log('AddDocument data' + data); var fd = new FormData(); fd.append('Attachment', f); $http.post('api/Document/' + $routeParams.changeId + '/AddDocument', fd, { method: 'POST', url: 'api/Document/' + $routeParams.changeId + '/AddDocument', data: fd, // I have tried application/x-www-form-urlencoded & application/octet-stream for the content type headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(response) { console.log(response.data); }); }; r.readAsArrayBuffer(f); }; } 

This code works fine as far as I can tell in that I do get a HttpRequestMessage in my code coming through (see below), however there are no headers that are passed through - but I can see the content-disposition when I do ReadAsStringAsync

[HttpPost]
[Route("api/Document/{id}/AddDocument")]
public async Task<string> Add(HttpRequestMessage request)
{
    var doc = await request.Content.ReadAsByteArrayAsync();

    var values = Enumerable.Empty<string>();

    // this is always null
    var header = (request.Content.Headers.TryGetValues(name: "filename", values: out values))
        ? values.First()
        : null;

    // this will be the following
    /*
     * ------WebKitFormBoundaryQIUoHBmcWJTY9cJx
Content-Disposition: form-data; name="Attachment"; filename="IMG_8639.JPG"
Content-Type: image/jpeg
    */
    var str = await request.Content.ReadAsStringAsync();

    // code that will add the byte array, filename, etc to a database table...

    return "success";
}

How do I pull out the filename from an uploaded file?

From the first part of your code Code, what you doing is trying to mimic a http request object and Post that to to your Web API. Then inside you Web APi stack, Web API is trying to map the object you posted to the built in HttpRequestMessage object.

public async Task<string> Add(HttpRequestMessage request)

is equivalent to:

public async Task<string> Add(FormData)

The HttpRequestMessage parameter is automatically bound so that you can get hold of request information in your controller method if you need to

I guess what you should be doing is create a Model object in C# (WEb API) that maps directly to your FormData object, then the API stack will bind it correctly, you can pass the headers in the main $http.Post request and read them in Web Api controller.

Hope this makes sense, I posted the whole code as I think the problem here is understanding of the concept. As an example check this Git Hub Sample , you can always adapt it to your needs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM