我將與文件上傳問題,其中我在前端使用角和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'是問題所在。設置標題不會添加邊界。您需要讓瀏覽器創建標題。不完全確定如何。如果我記得,它可能是像設置標題爲'假'或類似的東西。您應該搜索發送文件的文章。我相信他們會討論它。 –