[英]File Upload API working with Postman but not with AngularJS
我要处理文件上传问题,其中我在前端使用angular,在后端使用Java,并将图像上传到S3存储桶。 我认为Java代码中没有问题,因为当我在邮递员上使用此上传URL时,一切顺利,我将附加邮递员屏幕截图以展示其工作正常
这是我的AngularJS控制器 ,如下所示:
contactUs.controller('contactController', ['$scope','$http',
function($scope,$http) { $scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "uploadURL";
var fd = new FormData(file);
fd.append('files', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': 'multipart/form-data',
'Authorization': 'Basic QHN0cmlrZXIwNzoxMjM0NTY='}
})
.success(function(response){
console.log(response);
})
.error(function(error){
console.log(error);
});
};
}]);
这是我的AngularJS指令 ,如下所示:
contactUs.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
console.log(model);
console.log(modelSetter);
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
HTML如下:
<input type = "file" name="files" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
Java控制器如下:
@Path("/upload")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/text")
public Response uploadFile(@FormDataParam("files") List<FormDataBodyPart> bodyParts,@FormDataParam("files") FormDataContentDisposition fileDispositions) {
/* Save multiple files */
BodyPartEntity bodyPartEntity = null;
String fileName = null;
for (int i = 0; i < bodyParts.size(); i++) {
bodyPartEntity = (BodyPartEntity) bodyParts.get(i).getEntity();
fileName = bodyParts.get(i).getContentDisposition().getFileName();
s3Wrapper.upload(bodyPartEntity.getInputStream(), fileName);
}
String message= "File successfully uploaded !!";
return Response.ok(message).build();
}
我在AngularJS中遇到的错误如下:
400-错误的要求
1)要发布文件数据,您不需要提供content-type作为Multi part / form-data。 因为它自动了解数据类型。 因此,只需传递headers: {'Content-Type': undefined}
。
2)如邮递员所示,密钥是文件,那么如果您提供name="files"
和fd.append("files",file)
,则由于文件密钥在两侧,因此不会处理。 因此,从HTML删除name="files"
,然后处理上传文件。
通常,我在$http
使用以下命令来发送多部分表单数据。 请尝试这个。
var formdata = new FormData();
formdata.append('files', file);
return $http.post(uploadUrl, formdata, { transformRequest: angular.identity, headers: {'Content-Type': undefined} });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.