我可以成功地从AWS获得签名的URL,但我仍然得到一个错误,试图把一个文件。
//服务器. js
server.get('/...', (req, res) => {
const s3 = new AWS.S3();
const fileName = req.query.filename;
const fileType = req.query.filetype;
const s3Params = {
Bucket: '...',
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3Params, (err, signedUrl) => {
if (err) {
console.log('s3 signed url err', err);
return res.end();
}
const returnData = {
signedUrl,
url: `https://....s3.amazonaws.com/${fileName}`
};
res.send(JSON.stringify(returnData));
});
});
//React
class ImageUploader extends React.Component {
onDrop = files => {
// const file = files[0];
// const fileName = file.name;
var file = files[0];
axios.get('/...', {
params: {
filename: 'home/banner-images/' + file.name,
filetype: file.type
}
})
.then(result => {
const options = {
headers: {
'Content-Type': file.type,
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
};
const instance = axios.create();
return instance.put(result.data.signedUrl, file, options);
})
.then(result => {
console.log('then then result', result);
})
.catch(err => {
console.log('s3 put err', err);
});
};
render() {
return (
<div>
<Dropzone onDrop={this.onDrop}>
<div>
Try dropping a file here, or click to select a file to upload.
</div>
</Dropzone>
</div>
);
}
}
我的AWS策略:
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject"
],
"Resource": "arn:aws:s3:::.../*"
}
]
}
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
get请求成功获取signedUrl,但put请求返回错误:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
这是建立在Next.js之上的,这给了我很多问题,安装Cognito只用于客户端上传。
4条答案
按热度按时间t30tvxxf1#
我在我的react应用程序中也遇到了同样的问题。然后我用了“fetch”而不是“axios”,它工作得很好。看起来很奇怪,但在我的情况下工作。
vcudknz32#
不知道问题出在哪里,但这是我为React工作时使用预先签名的AWS S3链接上传文件的结果。
pn9klfpd3#
在浏览器中打开signedURL并检查响应
可能的错误:
yi0zb3m44#
我也遇到过这种情况,在HTTP中添加超时对我很有效。