gpt4 book ai didi

javascript - 尽管上传成功,但在 aws s3 中找不到图像

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:08 25 4
gpt4 key购买 nike

我正在使用 ng-file-upload 模块

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

我发现类似的问题Here 。我的 Angular 前端正是来自上面的两个链接。

 App.controller('MyCtrl2', ['$scope', '$http', 'Upload', '$timeout', function ($scope, $http, Upload, $timeout) {
$scope.uploadPic = function(file) {
var filename = file.name;
var type = file.type;
var query = {
filename: filename,
type: type
};
$http.post('/signing', query)
.success(function(result) {
Upload.upload({
url: result.url, //s3Url
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
delete headers.Authorization;
return data;
},
fields: result.fields, //credentials
method: 'POST',
file: file
}).progress(function(evt) {
console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
}).error(function() {

});
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
}]);

还有我的 Node 后端

app.post('/signing', function(req, res) {
var request = req.body;
var fileName = request.filename
var s3Url = 'https://' + aws.bucket + '.s3' + '.amazonaws.com/';
var extension = fileName.substring(fileName.lastIndexOf('.'));
var today = new Date();
var path = '/' + today.getFullYear() + '/' + today.getMonth() + '/' + today.getDate() + '/' + uuid.v4() + extension;

var readType = 'private';

var expiration = moment().add(5, 'm').toDate(); //15 minutes

var s3Policy = {
'expiration': expiration,
'conditions': [{
'bucket': aws.bucket
},
['starts-with', '$key', path],
{
'acl': readType
},
{
'success_action_status': '201'
},
['starts-with', '$Content-Type', request.type],
['content-length-range', 2048, 10485760], //min and max
]
};

var stringPolicy = JSON.stringify(s3Policy);
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');

// sign policy
var signature = crypto.createHmac('sha1', aws.secret)
.update(new Buffer(base64Policy, 'utf-8')).digest('base64');

var credentials = {
url: s3Url,
fields: {
key: path,
AWSAccessKeyId: aws.key,
acl: readType,
policy: base64Policy,
signature: signature,
'Content-Type': request.type,
success_action_status: 201
}
};
res.jsonp(credentials);
});

当我上传时,我的请求得到了积极的回应。但在我的桶中找不到该图像。我想将我的 fileNAME 添加到 s3Url 中。就像

var s3Url = 'https://' + aws.bucket + '.s3' +  '.amazonaws.com/' + fileName;

它失败并返回禁止错误。我注意到上面的 path 变量,文件名不应附加到 s3Url 中。我尽了一切努力,但我的文件没有显示在存储桶中。请问我做错了什么,导致文件无法上传或显示?任何帮助将不胜感激。

最佳答案

如果您通过表单提交文件,那么以下代码可能会对您有所帮助。

exports.uploadImageToS3Bucket = function(res, file, folder, callback) {
var fs = require('node-fs');
var AWS = require('aws-sdk');


var filename = file.name; // actual filename of file
var path = file.path; //will be put into a temp directory
var mimeType = file.type;

var accessKeyId = config.get('s3BucketCredentials.accessKeyId');
var secretAccessKeyId = config.get('s3BucketCredentials.secretAccessKey');
var bucketName = config.get('s3BucketCredentials.bucket');

var timestamp = new Date().getTime().toString();
var str = '';
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var size = chars.length;
for (var i = 0; i < 5; i++) {
var randomnumber = Math.floor(Math.random() * size);
str = chars[randomnumber] + str;
}
filename = filename.replace(/\s/g, '');
var fileNewName = str + timestamp + "-" + filename;

fs.readFile(path, function(error, file_buffer) {
if (error) {
responses.imageUploadError(res,{});
}
AWS.config.update({accessKeyId: accessKeyId, secretAccessKey: secretAccessKeyId});
var s3bucket = new AWS.S3();


var params = {Bucket: bucketName, Key: folder + '/' + fileNewName, Body: file_buffer, ACL: 'public-read', ContentType: mimeType};
s3bucket.putObject(params, function(err, data) {
if (err) {
console.log(err);
responses.imageUploadError(res,{});
} else {
return callback(fileNewName);
}
});
});
};

但我建议您使用base64encoder,因为您可以直接从 Node 服务器将对象放入s3中,并将内容类型设置为文件类型/扩展名。在大多数情况下,首选这种 Base64 方法,因为它不需要您通过 http 发送文件。

关于javascript - 尽管上传成功,但在 aws s3 中找不到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com