gpt4 book ai didi

javascript - 尝试上传到 aws s3 存储桶时收到 400 Bad Request

转载 作者:搜寻专家 更新时间:2023-10-31 23:23:36 25 4
gpt4 key购买 nike

我在我的服务器上对 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, 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

https://mybucket.s3.amazonaws.com/a33b4a43f23fc41de9ddck1k?AWSAccessKeyId=ADIFJDGPMRFRGLXSYWPQ&Content-Type=image%2Fpng&Expires=1496716543&Signature=0zcx%2BFzWUoeFD02RF2CQ2o0bLmo%3D&x-amz-acl=public-read

然后当我在客户端上返回该 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) Bad Request

最佳答案

我遇到了同样的问题,在搜索了几个小时之后,我能够通过将我的存储桶区域添加到我使用 s3.getSignedUrl() .

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
}
});

希望这能解决您的问题。

关于javascript - 尝试上传到 aws s3 存储桶时收到 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44380577/

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