Oam Psy Oam Psy - 4 months ago 34
Javascript Question

File object empty when sending to server ng-file-upload

Im using ng-file-upload to upload a basic single file to my server.

I can select the file, see the file name i have selected, and pass the file object (

$scope.myFiles[0]
) to my angular service. However, when populating my HTTP data property with the file, inspecting the HTTP request in dev tools, file is empty object.

Controller:

UploadService.upload( { data: { file: $scope.myFiles[0], 'category': $scope.selectedCategory}})
.success(function (data) {
////
////


UploadService:

app.factory('UploadService', function ($http, $q) {
return {
upload: function (something) {
console.log(something);

return $http({
method: 'POST',
url: '/upload',
data: something
});
}
}
});


With the above, inspecting in dev tools HTTP requests, i see:

Request Payload:
{data: {file: {}, category: "Friend Card"}}
data:
{file: {}, category: "Friend Card"}
category:"Friend Card"
file:{}


Looking at the output of console.log(something), i can see the file via:

{
$hashKey:"object:107"
lastModified:1465716430000
lastModifiedDate:Sun Jun 12 2016 08:27:10 GMT+0100 (BST)
name:"Postcard.JPG"
size:522622
type:"image/jpeg"
webkitRelativePath:""
}





Have changed function to have a header type via:

return $http({
method: 'POST',
url: '/upload',
headers: {
'Content-Type': something.data.file.type
},
data: {
"file": something.data.file,
"category": something.data.category
}
});


I can see in dev tools:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:48
Content-Type:image/jpeg
Cookie:_ga=GA1.1.2023678669.1463291637; _gat=1
Host:localhost:8585
Origin:http://localhost:8585
Referer:http://localhost:8585/pages/


Specifically: Content-Type:image/jpeg so it looks correct, however file is still and empty object.

Answer

Answer came partly from danial above...

The ng-file-upload lib comes with a number of API's and methods that can be injected in to your angular app, one of which is 'Upload' service.

I injected this in to my controller, and followed the jsFiddle here: http://jsfiddle.net/danialfarid/maqbzv15/1118/

Upload.upload({
  url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
  data: {username: $scope.username, file: file},
});