Upload Images to S3 from Node Back End


This video is part of the following playlists:


Learn how to store your express server's image files in an s3 bucket.

There is an updated version to this tutorial. Use the new one instead:

Chapters:

  • 0:00​ Intro
  • 1:23​ Using Multer to POST the image to the server
  • 4:36 Setting up the S3 bucket
  • 6:38 Creating an IAM Policy for the bucket
  • 9:10 Creating an IAM User for the server
  • 11:27 Installing the AWS SDK
  • 14:00 Uploading the image to S3
  • 18:08 Downloading the image from S3
  • 22:28 Removing images from the server
  • 25:37 Conclusion

Code:

https://github.com/Sam-Meech-Ward/image-upload-s3

import { useState } from 'react'
import axios from 'axios'

import './App.css'

async function postImage({image, description}) {
  const formData = new FormData();
  formData.append("image", image)
  formData.append("description", description)

  const result = await axios.post('/images', formData, { headers: {'Content-Type': 'multipart/form-data'}})
  return result.data
}


function App() {

  const [file, setFile] = useState()
  const [description, setDescription] = useState("")
  const [images, setImages] = useState([])

  const submit = async event => {
    event.preventDefault()
    const result = await postImage({image: file, description})
    setImages([result.image, ...images])
  }

  const fileSelected = event => {
    const file = event.target.files[0]
    setFile(file)
  }

  return (
    <div className="App">
      <form onSubmit={submit}>
        <input onChange={fileSelected} type="file" accept="image/*"></input>
        <input value={description} onChange={e => setDescription(e.target.value)} type="text"></input>
        <button type="submit">Submit</button>
      </form>

      { images.map( image => (
        <div key={image}>
          <img src={image}></img>
        </div>
      ))}

    </div>
  );
}

export default App;

Find an issue with this page? Fix it on GitHub