我正在处理文件上传问题,其中我在前端使用角度,在后端使用Java并在S3存储桶上传图像。我认为在java代码中没有问题,因为当我在邮递员上使用这个上传URL时它很顺利,我正在附加Postman截图来展示它是如何正常工作
以下是我的 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 - 错误请求
答案 0 :(得分:2)
1)要POST文件数据,您不需要提供内容类型作为多部分/表单数据。因为它自动了解数据类型。所以只需传递 headers: {'Content-Type': undefined}
。
2)当您在邮递员中显示时,键是文件然后如果您提供 name="files"
和 fd.append("files",file)
,它不会处理,因为文件密钥在两边。因此,从HTML中删除 name="files"
,然后处理上传文件。
答案 1 :(得分:1)
通常我使用以下$http
来发送多部分表单数据。请试试这个。
var formdata = new FormData();
formdata.append('files', file);
return $http.post(uploadUrl, formdata, { transformRequest: angular.identity, headers: {'Content-Type': undefined} });