gpt4 book ai didi

javascript - 如何将react-s3-uploader与reactjs一起使用?

转载 作者:行者123 更新时间:2023-11-28 17:28:25 25 4
gpt4 key购买 nike

我是reactjs新手,想要在s3上上传图像,但不知道它是如何工作的......并且不知道我将从哪里获得来自aws的图像路径(在哪个函数中)?

这是我的 react 代码

import ApiClient from './ApiClient';  // where it comes from?

function getSignedUrl(file, callback) {
const client = new ApiClient();
const params = {
objectName: file.name,
contentType: file.type
};

client.get('/my/signing/server', { params }) // what's that url?
.then(data => {
callback(data); // what should I get in callback?
})
.catch(error => {
console.error(error);
});
}

我的服务器文件Server.js

AWS.config.setPromisesDependency(Bluebird)

AWS.config.update({
accessKeyId: 'accessKey',
secretAccessKey: 'secret',
region: 'ap-south-1'
})

const s3 = new AWS.S3({
params: {
Bucket: 'Bucketname'
},
signatureVersion: 'v4'
})

class S3Service {

static getPreSignedUrl(filename, fileType, acl = 'public-read') {
return new Bluebird(resolve => {
const signedUrlExpireSeconds = 30000
return resolve({
signedRequest : s3.getSignedUrl('putObject', {
Key: "wehab/"+filename,
ContentType:"multipart/form-data",
Bucket: config.get('/aws/bucket'),
Expires: signedUrlExpireSeconds
}),
url : `https://${config.get('/aws/bucket')}.s3.amezonaws.com/wehab/${filename}`
})
})
}

}

最佳答案

首先您需要创建 s3 存储桶并附加这些策略 如果存储桶名称是“DROPZONEBUCKET”(存储桶是全局唯一的)

政策

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:PutObject",
"s3:GetObject"
],
"Resource": "arn:aws:s3:::DROPZONEBUCKET/*"
}
]
}

CORS 配置

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>9000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

然后运行您的node.js 服务器并尝试上传文件。

一旦您选择上传文件,它将调用此 getSignedUrl(file, callback) 函数并返回 url。

成功获取此 URL 后,您就可以上传文件。

那么文件路径是https://s3.amazonaws.com/{BUCKET_NAME}/{FILE_NAME}

例如。

https://s3.amazonaws.com/DROPZONEBUCKET/profile.jpeg

像这样修改API

var s3Bucket = new AWS.S3();

var s3 = new Router({ mergeParams: true });

var params = {
Bucket: 'BUCKET_NAME', // add your s3 bucket name here
Key: data.filename,
Expires: 60,
ContentType: data.filetype
};

s3Bucket.getSignedUrl('putObject', params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});

关于javascript - 如何将react-s3-uploader与reactjs一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017765/

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