Last active
November 9, 2022 15:36
-
-
Save leechunhoe/39d56215a618bd7dbe0b9919886beaea to your computer and use it in GitHub Desktop.
Minimal file upload React.js component
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
import React, { Component } from 'react'; | |
const S3 = require('aws-sdk/clients/s3'); | |
const AWS = require('aws-sdk'); | |
AWS.config.update({ | |
accessKeyId: [Your AWS access key ID (from ~/.bashrc)], | |
secretAccessKey: [Your AWS secret access key (from ~/.bashrc)] | |
}); | |
class FileUpload extends Component { | |
constructor () { | |
super(); | |
this.state = { | |
file: null, | |
s3: new AWS.S3({ | |
params: {Bucket: [Your S3 bucket name]} | |
}) | |
}; | |
} | |
submitFile = (event) => { | |
event.preventDefault(); | |
this.state.s3.upload({ | |
Key: [folder/filename.ext], | |
Body: this.state.file[0], | |
ACL: 'public-read' | |
}, (err, data) => { | |
if (err) { | |
console.log(err); | |
return alert('There was an error uploading your file: ', err.message); | |
} | |
alert('Upload file success.'); | |
}); | |
} | |
handleFileUpload = (event) => { | |
this.setState({file: event.target.files}); | |
} | |
render () { | |
return ( | |
<form onSubmit={this.submitFile}> | |
<input label='upload file' type='file' onChange={this.handleFileUpload} /> | |
<button type='submit'>Send</button> | |
</form> | |
); | |
} | |
} | |
export default FileUpload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment