Skip to content

Instantly share code, notes, and snippets.

@jordanburke
Last active December 29, 2020 22:44
Show Gist options
  • Save jordanburke/2bf85946d2bd716d3cf74c297291c46e to your computer and use it in GitHub Desktop.
Save jordanburke/2bf85946d2bd716d3cf74c297291c46e to your computer and use it in GitHub Desktop.
React Simple S3 Uploader
import React, {useState} from "react";
import axios from "axios";
import config from "../config"
const endpoint = config.apiGateway.URL;
export const Upload = () => {
const [file, setFile] = useState<File | undefined>()
const onFormSubmit = (e: any) => {
e.preventDefault() // Stop form submit
if (file) {
fileUpload(file).then((response) => {
console.log(response.data);
})
}
}
const onChange = (e: any) => {
setFile(e.target.files[0]);
}
const fileUpload = async (file: File) => {
return axios.get(`${endpoint}`).then((res) => {
console.log(res.data);
const url = res.data.url;
const config = {
headers: {
'content-type': file.type
}
}
return axios.put(url, file, config)
})
}
return (
<form onSubmit={onFormSubmit}>
<input type="file" onChange={onChange}/>
<button type="submit">Upload</button>
</form>
)
}
@FelipeBattistotti
Copy link

Hi Jordan,
How did you make the backend of this application?

@jordanburke
Copy link
Author

Hi Felipe,

I'm using Scala with Http4s, along with the awscala.s3.S3 package to make S3 Java lib a little less verbose to use. The main thing that the backend is doing above is providing short-lived signed URL and returning that in a JSON response for the client to use, so that it can upload to S3 directly without passing through my api/backend server.

For example:
val url = s3.generatePresignedUrl(BUCKET, key, exp, HttpMethod.PUT)

And pass that url val back in some json response (e.g., { url: string } above) at which the client can use it here (line 33):
return axios.put(url, file, config)

Honestly, most of the magic/work is just setting up the AWS S3 library with your keys, then generating those signed URLs to pass back at the clients request. Hope that helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment