我已经浏览了本网站上有关此主题的所有问题,并且几乎尝试了所有代码。以下是我从本网站上列出的答案中借鉴的最新片段。我正在尝试异步上传文件到AWS s3端点。我正确地获得了已签名的网址,但无法实际上传文件。
HTML:
<form name="Details" ng-controller="DetailsController">
<input type="file" file-input="files" />
<button ng-click="initUpload()">Upload</button>
</form>
fileInput Directive和DetailsController:
module.directive('fileInput', ['$parse', function ($parse) {
return {
restrict: 'A',
link:function(scope, elm, attrs){
elm.bind('change', function(){
$parse(attrs.fileInput)
.assign(scope, elm[0].files);
scope.$apply();
});
}
}
}]).controller("DetailsController", ["$scope", "PostalService",
function ($scope, PostalService) {
getSignedURLForUpload = function(userId, filename, filetype){
return (PostalService.getSignedURLForUpload(userId, filename, filetype));
};
$scope.initUpload = function(){
var signedUrl = getSignedURLForUpload($scope.userId, $scope.files[0].name,$scope.files[0].type);
signedUrl.then(function (data) {
var uploadPromise = PostalService.uploadFile($scope.files, data.signedRequest);
uploadPromise.then(function(result) {
$scope.awsurl = data.url;
});
});
};
]);
PostalService:
module.factory("PostalService",
["$resource",
function($resource) {
var functions = {
getSignedURLForUpload: function(userId, filename, filetype) {
var SignUrl = $resource("host end point?userid="+userId+"&file-name="+filename+"&file-type="+filetype);
var promise = SignUrl.get().$promise;
return promise;
},
uploadFile: function(file, signedRequest) {
var Upload = $resource(signedRequest, null, {
'save':{
method: 'POST',
transformRequest: function(data){
var fd = new FormData();
angular.forEach(data, function(value, key) {
if(value instanceof FileList) {
if(value.length ===1){
fd.append(key, value[0]);
}else {
angular.forEach(value, function(file, index){
fd.append(key+'_'+index, file);
});
}
}else {
fd.append(key, value);
}
});
return fd;
},
headers: {'Content-Type' : undefined}
}
});
var promise = Upload.save(file).$promise;
return promise;
}
};
return functions;
}
]);
答案 0 :(得分:0)
所以问题在于实现PostalService的uploadFile功能。
标题需要正确设置: 1.&#39;内容类型&#39; :&#39; image / jpeg&#39; 2.授权:&#39; undefined&#39;
我的应用程序正在自动设置授权标头,在这种情况下,我必须使它们无效,因为用于将文件上传到服务器的特定URL链接已预先签名,签名是查询的一部分。
内容类型必须是&#39; image / jpeg&#39;并且没有像我的后端服务器所期望的那样未定义。
最后,方法&#39; POST&#39;没有工作。不得不用&#39; PUT&#39;代替。