I had similar problem when had to upload file and send user token info at the same time. transformRequest
along with forming FormData
helped:
$http({
method: 'POST',
url: '/upload-file',
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
email: Utils.getUserInfo().email,
token: Utils.getUserInfo().token,
upload: $scope.file
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
For getting file $scope.file
I used custom directive:
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Html:
<input type="file" file="file" required />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…