我正在尝试按照本教程使用NodeJS将文件上传到Amazon S3,并且已经挂断了代码客户端上发生的错误,但我很确定是我的路线的一部分。出现的404错误位于xhr.send()
函数中对服务器的sign_request
请求中。我在GET中记录的文件中的信息是正确的file:138 GET http://localhost:3000/sign?file_name=gtm-value.png&file_type=image/png 404 (Not Found)
,这让我觉得它与我的路线设置有关。
视图:
<!DOCTYPE html>
<head>
{{> app/app-head}}
</head>
<body>
{{> app/app-navigation}}
<div class="container">
<div class="col-md-12">
<form action="/create" method="post">
<input type="file" name="fileAttachment" id="image">
<img id="preview">
<button type="submit" id="button">Create Image</button>
</form>
</div>
<script type="text/javascript">
function upload(file, signed_request, url, done) {
var xhr = new XMLHttpRequest();
xhr.open("PUT", signed_request);
xhr.setRequestHeader('x-amz-acl', 'public-read');
xhr.onload = function() {
if (xhr.status === 200) {
done()
};
};
xhr.send(file);
}
function sign_request(file, done) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/sign?file_name=" + file.name + "&file_type=" + file.type);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
done(response);
}
};
xhr.send();
};
document.getElementById("image").onchange = function() {
var file = document.getElementById("image").files[0]
if (!file) return
sign_request(file, function(response) {
upload(file, response.signed_request, response.url, function() {
document.getElementById("preview").src = response.url
});
});
};
</script>
路线:
var aws = require('aws-sdk');
appRoutes.get('/sign', function(req, res){
aws.config.update({accessKeyId: config.awsAccessKeyId, secretAccessKey: config.awsSecretAccessKey});
var s3 = new aws.S3();
var options = {
Bucket: config.awsBucket,
Key: req.query.file_name,
Expires: 60,
ContentType: req.query.file_type,
ACL: 'public-read'
}
s3.getSignedUrl('putObject', options, function(err, data){
if(err) return res.send('Error with S3')
res.json({
signed_request: data,
url: 'https://s3.amazonaws.com/' + config.awsBucket + '/' + req.query.file_name
});
});
});
答案 0 :(得分:0)
该问题与代码无关,并且使用auth密钥向用户提供的权限存在问题。在为用户提供AdministrativeAccess策略后,问题已得到解决。