Javascript 尝试上载到aws s3 bucket时收到400个错误请求
我在服务器上对URL进行签名,然后将其发送回运行正常的客户端。这就是函数的外观Javascript 尝试上载到aws s3 bucket时收到400个错误请求,javascript,node.js,reactjs,amazon-web-services,amazon-s3,Javascript,Node.js,Reactjs,Amazon Web Services,Amazon S3,我在服务器上对URL进行签名,然后将其发送回运行正常的客户端。这就是函数的外观 const aws = require('aws-sdk'), config = require('config'), crypto = require('crypto'); module.exports = async function(file_type) { aws.config.update({accessKeyId: config.AWS_ACCESS_KEY, secretA
const aws = require('aws-sdk'),
config = require('config'),
crypto = require('crypto');
module.exports = async function(file_type) {
aws.config.update({accessKeyId: config.AWS_ACCESS_KEY, secretAccessKey: config.AWS_SECRET_KEY})
const s3 = new aws.S3();
try {
if (!file_type === "image/png") {
return ({success: false, error: 'Please provide a valid video format'});
}
let buffer = await crypto.randomBytes(12);
let key = buffer.toString('hex');
let options = {
Bucket: config.AWS_S3_BUCKET,
Key: key,
Expires: 60,
ContentType: file_type,
ACL: 'public-read',
}
let data = await s3.getSignedUrl('putObject', options);
console.log('data was', data)
return ({
success: true,
signed_request: data,
url: ('https://s3.amazonaws.com/' + config.AWS_S3_BUCKET + '/' + key),
key,
});
} catch (error) {
console.log('the error was', error)
return ({
success: false,
error: error.message,
})
}
}
所以这个很好用,最后我得到了一个像
然后,当我在客户端上获得该url时。。我使用axios发送PUT请求,其函数如下-
function uploadToS3(file, signedRequest, callback){
var options = {
headers: {
'Content-Type': file.type
}
};
axios.put(signedRequest, file, options)
.then(result =>{
console.log('the result was', result)
callback(result)
})
.catch(err =>{
callback(err)
})
}
我得到的唯一回复是(400)错误请求猜测您提供的错误头 为我工作
function upload(file, signedRequest, done) {
const xhr = new XMLHttpRequest();
xhr.open('PUT', signedRequest);
xhr.setRequestHeader('x-amz-acl', 'public-read');
xhr.onload = () => {
if (xhr.status === 200) {
done();
}
};
xhr.send(file);
}
我遇到了同样的问题,在搜索了几个小时后,我能够通过将我的bucket区域添加到服务器端后端来解决这个问题,在那里我使用s3.getSignedUrl()请求一个签名URL
const s3 = new AWS.S3({
accessKeyId:"your accessKeyId",
secretAccessKey:"your secret access key",
region:"ap-south-1" // could be different in your case
})
const key = `${req.user.id}/${uuid()}.jpeg`
s3.getSignedUrl('putObject',{
Bucket:'your bucket name',
ContentType:'image/jpeg',
Key:key
}, (e,url)=>{
res.send({key,url})
})
在获得签名的URL后,我在客户端使用axios.put()使用URL将图像上传到我的s3存储桶中
const uploadConf = await axios.get('/api/uploadFile');
await axios.put(uploadConf.data.url,file, {
headers:{
'Content-Type': file.type
}
});
希望这能解决您的问题。我正试图用axios实现这一点。上面是我以前是怎么做的,所以我只是再次使用它。lolI也有同样的问题,但在AWS.S3对象中添加了region属性和Bucket的正确区域后,我救了我的命:)谢谢