Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Created October 31, 2019 19:09
Show Gist options
  • Save brunoksato/bd92ef358d5c82c48be057485ba12f50 to your computer and use it in GitHub Desktop.
Save brunoksato/bd92ef358d5c82c48be057485ba12f50 to your computer and use it in GitHub Desktop.
//component
<Dropzone
onDrop={async acceptedFiles => {
if (acceptedFiles.length > 1) {
toaster.warning("Limite 1 imagem");
return;
}
const files = [];
for (const file of acceptedFiles) {
const fileName = await Upload("pasta-no-s3", file);
files.push({ name: fileName });
}
files.forEach(item => {
setImagem({ image: item.name });
});
setMainImage(files);
}}
>
{({ getRootProps, getInputProps }) => (
<SectionGallery>
<div {...getRootProps()}>
<input {...getInputProps()} />
{mainImage.length === 0 && (
<p> #1 Selecione a imagem principal</p>
)}
{mainImage.map((item, idx) => (
<img
key={idx}
src={`${process.env.REACT_APP_ASSETS_BUCKET}/pasta/${item.name}`}
width="100px"
height="100px"
/>
))}
</div>
</SectionGallery>
)}
</Dropzone>
// upload
import AWS from "aws-sdk/global";
import S3 from "aws-sdk/clients/s3";
export const IMAGE_URL = `${process.env.REACT_APP_ASSETS_BUCKET}`;
export const S3_NAME = `${process.env.REACT_APP_ASSETS_BUCKET_NAME}`;
export async function Upload(folder, file) {
const creds = {
bucket: `${S3_NAME}/${folder}`,
access_key: process.env.REACT_APP_ACCESS_KEY,
secret_key: process.env.REACT_APP_SECRET_KEY
};
if (file === null) {
return null;
}
const extension = file.type.split("/")[1];
const name = file.name.split(".")[0];
const fileName = `${name}-${new Date().getTime()}.${extension}`;
AWS.config.update({
accessKeyId: creds.access_key,
secretAccessKey: creds.secret_key
});
AWS.config.region = "sa-east-1";
const bucket = new S3({ params: { Bucket: creds.bucket, Key: fileName } });
const params = {
Key: fileName,
ContentType: file.type,
Body: file,
ServerSideEncryption: "AES256"
};
await bucket.putObject(params).promise();
return fileName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment