我将与文件上传问题,其中我在前端使用角和Java在后端和上传图像在S3桶。我认为这是在Java代码中没有问题,因为当我使用的邮递员它会好这个上传网址,我附上邮差截图来展示它是如何工作的罚款文件上传API使用邮递员,但不是与AngularJS
这里是我的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>
的爪哇控制器如下:
@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 -
我觉得这个'Content-Type':'multipart/form-data'是问题所在。设置标题不会添加边界。您需要让浏览器创建标题。不完全确定如何。如果我记得,它可能是像设置标题为'假'或类似的东西。您应该搜索发送文件的文章。我相信他们会讨论它。 –