Skip to content

Instantly share code, notes, and snippets.

@jordanburke

jordanburke/Upload.tsx

Last active Dec 29, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@FelipeBattistotti FelipeBattistotti commented Nov 11, 2020

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

@jordanburke

This comment has been minimized.

Copy link
Owner Author

@jordanburke jordanburke commented Nov 12, 2020

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