我有一个Anggular / NodeJS应用程序,我可以将图像上传到AWS S3。我已经尝试过NodeJS部分,它在使用Postman测试时有效,但我无法从客户端获取图像。如何获取图像并成功将其加载到S3?我在NodeJS部分使用AWS-sdk和Multer,在Angular上使用ng-file-upload指令。
查看:
<div ng-if="!user.imageurl">
No Image here
<img ngf-src="$scope.picture" style="width:100px; height:100px">
<input ngf-select
id="file"
type="file"
ng-model="$scope.picture"
ngf-accept="'image/\*'">
<button type="button" ng-click="$scope.uploadImage($scope.picture)">Upload Image</button>
</div>
客户端服务器:
.factory('UploadFac', function($http) {
var urlBase = mainsite + "image";
var _UploadService = {};
_UploadService.uploadProPic = function(image) {
var fd = new FormData();
fd.append('file', image);
return $http({
method: 'POST',
url: urlBase,
data: fd,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
return _UploadService;
})
控制器:
//export image upload
exports.uploadImage = function(req, res) {
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});
var s3 = new aws.S3({signatureVersion: 'v4'});
var key = 'Give your Image a name';
var image = req.files[0];
var s3_params = {
Bucket: S3_BUCKET,
Key: key,
ContentType: image.mimetype,
ACL: 'public-read',
Body: image.buffer
};
return s3.putObject(s3_params, function(err, data) {
if(err) {
res.json({ status: 500, success: false, message: err});
} else {
res.json({
status: 200,
success: true,
message: 'Image uploaded',
data: 'https://'+ S3_BUCKET +'.s3.amazonaws.com/' + key
});
}
});
};