AngularJS how to send multipart/mixed

北慕城南 提交于 2019-12-04 16:58:05

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!");
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!