2

我正在做一个项目,我必须在 AngularJS 中使用文件上传一小部分 JSON。

我已经使用 Danial Farid 的 angular-file-upload 编写了代码,它正在工作,除了它总是发送“multipart/form-data,boundary=<whatever>”

但是,我必须使用多部分/混合。

这是我的电话:

$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);
});

有没有办法在发送之前修改标题?

如果不使用他的角度文件上传,那么通过另一种方法,希望不必“滚动我自己的”功能?

编辑1:

我只是无法理解做出这种改变怎么会如此困难。当然可以添加

headers: {'Content-Type': 'multipart/mixed'}

但这绝对没有任何作用,因为没有边界。为什么不能有办法把边界拉出来?就像是

headers: {'Content-Type': 'multipart/mixed, boundary=%b'}

我需要尽快让这个工作。

4

1 回答 1

6

我不能再等了。我最终推出了自己的产品,它确实有效。这是代码......希望其他人可以受益。

file_contents 是 reader.readAsArrayBuffer($scope.files[0]); 的输出

您需要从序言文本、文件数据和页脚构建一个 blob,因为否则将二进制数据附加到字符串将对二进制文件数据进行转换并且它将无法正常工作。

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!");
});
于 2015-01-26T00:31:45.200 回答