Skip to content

Instantly share code, notes, and snippets.

@leechunhoe
Last active November 9, 2022 15:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leechunhoe/39d56215a618bd7dbe0b9919886beaea to your computer and use it in GitHub Desktop.
Save leechunhoe/39d56215a618bd7dbe0b9919886beaea to your computer and use it in GitHub Desktop.
Minimal file upload React.js component
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