尝试上传到AWS S3存储桶时收到400错误请求 [英] getting 400 Bad Request when trying to upload to aws s3 bucket
问题描述
我在服务器上签署了URL,然后将其发送回客户端,效果很好.该函数的外观就是这样
I sign the URL on my server and send it back to the client which works fine. This is how that function looks
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,
})
}
}
所以这很好用,最后得到一个像这样的网址
So this works fine and winds up getting me a url like
然后,当我在客户端上获得该URL时..我使用axios发送具有--
Then when I get that url back on the client.. i send a PUT request using axios with a function like -
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)错误的请求
The only I'm getting back is (400) Bad Request
推荐答案
我遇到了同样的问题,经过几个小时的搜索,我能够通过将存储桶的区域添加到我请求的服务器端后端来解决此问题使用 s3.getSignedUrl()签名的URL.
I faced the same issue and after searching for hours, I was able to solve it by adding the region of my bucket to the server side backend where I was requesting a signed URL using 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存储桶中.
After getting the signed URL, I used axios.put() at the client side to upload the image to my s3 bucket using the URL.
const uploadConf = await axios.get('/api/uploadFile'); await axios.put(uploadConf.data.url,file, { headers:{ 'Content-Type': file.type } });
希望这可以解决您的问题.
Hope this solves your issue.
这篇关于尝试上传到AWS S3存储桶时收到400错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!