I'm using angular 1.5 and I have to hit a service to upload a file. In the same service I have to pass a JSON as request body too.
When I'm using Content-type: application/json
multipart for file is not working, if I use Content-type: undefined
then multipart will work but JSON param wont work. So is there any way like I can set a value
of a key-value
pair of a json as a multipart
? Or any other way to do this?
Thanks
Try it like this way and you will be fine:
$scope.uploadMultipart = function(file, jsonObject, uploadUrl){
var formData = new FormData();
formData.append('json',JSON.stringify(jsonObject));
formData.append('file', file);
return $http({
url: uploadUrl,
method: 'POST',
data: formData,
headers: { 'Content-Type': undefined},
transformRequest: angular.identity
});
};
I would not recommend it but thats how you could add the file as a part of a JSON object. In that way you be able to post a in content-type application/json
.
$scope.uploadHack = function(file, jsonObject, uploadUrl){
var aReader = new FileReader();
aReader.readAsText(file, "UTF-8");
aReader.onload = function (evt) {
//append file to json as raw data
jsonObject.file = {
content: aReader.result,
name: file.name,
size: file.size
};
$http({
url: uploadUrl,
method: 'POST',
data: jsonObject,
headers: { 'Content-Type': 'application/json'},
transformRequest: angular.identity
});
}
};