我知道有一种方法可以使用 POST 直接从 Web 浏览器上传到 S3,而无需将文件发送到后端服务器。但是有没有办法从 URL 而不是网络浏览器做到这一点。
例如,上传位于 http://example.com/dude.jpg 的文件使用 post 直接到 S3。我的意思是我不想将 Assets 下载到我的服务器然后将其上传到 S3。我只想向 S3 发出 POST 请求,它会自动上传。
最佳答案
我想我应该分享我的代码来实现类似的东西。我在后端工作,但可能可以在前端做类似的事情,但要注意 AWS 凭证 可能是暴露 .
出于我的目的,我想从外部 URL 下载文件,然后最终取回上传文件的 URL 表单 S3。
我也用过 axios
为了获得可上传的格式和 file-type
获得正确类型的文件,但这不是要求。
以下是我的代码片段:
async function uploadAttachmentToS3(type, buffer) {
var params = {
//file name you can get from URL or in any other way, you could then pass it as parameter to the function for example if necessary
Key : 'yourfolder/directory/filename',
Body : buffer,
Bucket : BUCKET_NAME,
ContentType : type,
ACL: 'public-read' //becomes a public URL
}
//notice use of the upload function, not the putObject function
return s3.upload(params).promise().then((response) => {
return response.Location
}, (err) => {
return {type: 'error', err: err}
})
}
async function downloadAttachment(url) {
return axios.get(url, {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
return (async () => {
let type = (await FileType.fromBuffer(buffer)).mime
return uploadAttachmentToS3(type, buffer)
})();
})
.catch(err => {
return {type: 'error', err: err}
});
}
let myS3Url = await downloadAttachment(url)
我希望它可以帮助那些仍在为类似问题而苦苦挣扎的人。祝你好运!
关于amazon-web-services - 是否可以使用 POST 直接从 URL 上传到 S3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7586533/