我试图上传一个文件到服务器使用angularjs和Spring(到amazonaws)。
File Upload using AngularJS
How to upload a file with AngularJS?
还查了youtube上的教程,找到了Black Cloud,Brent Aureli的频道,我就是搞不懂。
你必须在我的webapp中进行身份验证才能发送post请求,但我在登录时也会遇到错误。
非常感谢您的帮助。
<form>
<input type="file" file-model="file">
<button ng-click="submit()" type="submit">Click</button>
</form>
文件模型的指令:
.directive('fileModel', ['$parse', function($parse){
return {
restrict: 'A',
link: function(scope, element,attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
})
})
}
}
}])
控制器:
.controller('UploadController', ['$scope', 'multipartForm', function($scope, multipartForm) {
$scope.file = {};
$scope.submit = function() {
var uploadUrl = '/uploadtest';
multipartForm.post(uploadUrl, $scope.file);
}
}])
multipartForm服务:
.service('multipartForm', ['$http', function($http){
this.post = function(uploadUrl, data) {
var fd = new FormData();
for(var key in data) {
fd.append(key, data[key]);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}])
弹簧端点:
@RestController
@RequestMapping("/storage/")
public class BucketController {
private AmazonClient amazonClient;
@Autowired
public BucketController(AmazonClient amazonClient) {
this.amazonClient = amazonClient;
}
@RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
public String uploadFile(@RequestParam(value = "file") MultipartFile file) {
System.out.println("Uploading file!!!!!!!!!!!!");
return this.amazonClient.uploadFile(file);
}
}
浏览器中出现错误:
角度。js:15018可能未处理的拒绝:
“状态”:400,
“config”:{“method”:“POST”,“transformResponse”:[null],
“jsonpCallbackParam”:“回调”,
“headers”:{“Accept”:“应用程序/json,
/
",
“X-request-With”:“XMLHttpRequest”,
“基本c3p5bW9uc3R1c3pla0BnbWFpbC5jb206dGVzdA=”,
“X-XSRF-TOKEN”:“395d1e27-a6ee-4948-b673-39d31902e1ae”},
“url”:“/uploadtest”,“data”:{}},
“statusText”:“”,“xhrStatus”:“完成”}