angularjsngresource

Can't get the hang of FormData and ngResource


I'm trying to upload a file as MIME/multipart via AngularJS 1.6.4 and then send it off to an ASP.Net WebAPI. I have referenced a sample project that uses version 1.3.1, where the following works:

 var formData = new FormData(); 

 angular.forEach(photos, function (photo) { 
      formData.append(photo.name, photo); 
 }); 

 return photoManagerClient.save(formData) 
                                    .$promise 
                                    .then(function (result) { 
                                        if (result && result.photos) { 
                                            result.photos.forEach(function (photo) { 
                                                if (!photoExists(photo.name)) { 
                                                    service.photos.push(photo); 
                                                } 
                                            }); 
                                        } 
.
.
.
function photoManagerClient($resource) { 
    return $resource("api/photo/:fileName", 
            { id: "@fileName" }, 
            { 
                'save': { method: 'POST', transformRequest: angular.identity, headers: { 'Content-Type': undefined } }
            }); 
} 

I can't get this to work using 1.6.4 and I can't find the reason. The MIME/multipart header isn't there with 1.6.4, so I have been reading the bytes directly from the content, and yet I can't get the filename in this way.

It's obvious that the FormData is actually making it across because I can access the bytes in the request.

I have seen other answers/docs advise adding a transformRequest function because otherwise the Content-Type defaults to JSON. But when I do this, that code does not execute so the file is missing from the request on the server side.

I'm a bit lost here and was hoping there was an obvious reason for this difference between 1.3.1 and 1.6.4 that someone could point me toward.

Edit to add request headers:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:31761
Content-Type:application/json;charset=utf-8
Host:localhost:40981
Origin:http://localhost:51609
Referer:http://localhost:51609/app/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3266.0 Safari/537.36


Solution

  • Check the header request at Network in dev-tools, maybe it useful. If is not work, paste the header reuqest maybe can provide more information.