我正在处理文件上传问题,其中我在前端使用 Angular,在后端使用 Java,并在 S3 存储桶上上传图像。我认为 java 代码中没有问题,因为当我在 postman 上使用此上传 URL 时,一切进展顺利,我附上 postman 屏幕截图来展示它如何正常工作
这是我的 AngularJS Controller ,如下所示:
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 Controller 如下:
@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) 要 POST 文件数据,您不需要提供多部分/表单数据的内容类型。因为它自动理解数据类型。因此,只需传递 headers: {'Content-Type': undefined}
。
2)正如您在 postman 中所示,关键是文件,那么如果您提供name="files"
和 fd.append("files",file)
, 由于files key 两边都有,所以不会处理。因此,从 HTML 中删除 name="files"
并处理上传文件。
关于javascript - 文件上传 API 可与 Postman 配合使用,但不能与 AngularJS 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965181/