Created
August 25, 2019 14:44
-
-
Save Ifmr24/e597b66516a3db667592122046fda9a1 to your computer and use it in GitHub Desktop.
Upload files from react to s3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var aws = require('aws-sdk'); | |
aws.config.update({ | |
region: 'us-east-1', | |
accessKeyId: process.env.AWSAccessKeyId, | |
secretAccessKey: process.env.AWSSecretKey | |
}) | |
const S3_BUCKET = process.env.bucket | |
router.post("/api/uploadavatar", async (req, res) => { | |
const s3 = new aws.S3(); | |
const fileName = req.body.fileName; | |
const fileType = req.body.fileType; | |
const s3Params = { | |
Bucket: S3_BUCKET, | |
Key: fileName, | |
Expires: 500, | |
ContentType: fileType, | |
ACL: 'public-read' | |
}; | |
s3.getSignedUrl('putObject', s3Params, (err, data) => { | |
if (err) { | |
console.log(err); | |
res.json({ success: false, error: err }) | |
} | |
const returnData = { | |
signedRequest: data, | |
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}` | |
}; | |
res.json({ success: true, data: { returnData } }); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function | |
const [success, setSuccess] = useState(false); | |
const [url, setUrl] = useState(null); | |
const uploadInput = useRef(); | |
let uploadFile = async (e) => { | |
setSuccess(false) | |
e.preventDefault(); | |
let file = uploadInput.current.files[0]; | |
let fileParts = uploadInput.current.files[0].name.split('.'); | |
let fileName = shortid.generate() + "_" + fileParts[0]; | |
let fileType = fileParts[1]; | |
await axios.post("http://localhost:5000/api/uploadavatar", { | |
fileName, | |
fileType | |
}).then(async res => { | |
let data = res.data.data.returnData; | |
let signedRequest = data.signedRequest | |
setUrl(data.url) | |
let options = { | |
headers: { | |
'Content-Type': fileType | |
} | |
}; | |
await axios.put(signedRequest, file, options) | |
.then(res => { | |
console.log('archivo subido correctamente') | |
setSuccess(true) | |
}).catch(err => { | |
console.log('error al put archivo ', err) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment