I am working on a project where I have to upload a small bit of JSON with a file, working in AngularJS.
I've written code using Danial Farid's angular-file-upload, and it is working, except, it always sends "multipart/form-data, boundary=<whatever>"
However, I MUST use multipart/mixed.
This is my call:
$scope.upload = $upload.upload({
url: <my url>,
method: 'POST',
data: $scope.data,
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
Is there a way to modify the headers just before it gets sent?
If not using his angular-file-upload, then by another method, hopefully without having to 'roll my own' function?
Edit 1:
I just cannot understand how it can be so difficult to make this change. Of course you can add
headers: {'Content-Type': 'multipart/mixed'}
But this does absolutely NOTHING because there is no boundary. Why can't there be a way to pull the boundary out? Something like
headers: {'Content-Type': 'multipart/mixed, boundary=%b'}
I need to get this working ASAP.
I couldn't wait any longer. I ended up rolling my own and it does work. Here's the code...hopefully others can benefit.
file_contents is the output from reader.readAsArrayBuffer($scope.files[0]);
You need to build up a blob from the preamble text, the file data and the footer, because otherwise appending binary data to a string will do conversions on the binary file data and it will not work properly.
var epochTicks = 621355968000000000;
var ticksPerMillisecond = 10000;
var yourTicks = epochTicks + ((new Date).getTime() * ticksPerMillisecond);
var boundary='---------------------------'+yourTicks;
var header="--"+boundary+"\r\n";
var footer="\r\n--"+boundary+"--\r\n";
var contenttype="multipart/mixed; boundary="+boundary;
var contents=header+"Content-Disposition: form-data; name=\"json\"\r\n";
contents+="Content-Type: application/json\r\n";
contents+="Content-Length: "+JSON.stringify(data).length+"\r\n\r\n";
contents+=JSON.stringify(data)+"\r\n";
contents+=header+"Content-Disposition: form-data; name=\"image\"; filename=\""+$scope.files[0].name+"\"\r\n";
contents+="Content-Transfer-Encoding: binary\r\n";
contents+="Content-Type: "+$scope.files[0].type+"\r\n";
contents+="Content-Length: "+$scope.files[0].size+"\r\n\r\n";
blob=new Blob([contents,file_contents,footer]);
$http.post(restUrl+"user/avatar/uploadAvatar",blob,{'headers':{'Content-Type':contenttype}}).
success(function (data, status, headers, config) {
alert("success!");
}).
error(function (data, status, headers, config) {
alert("failed!");
});