DEV Community

ivan chiou
ivan chiou

Posted on

Medusa images uploading using Imgur API

Medusa is very powerful, useful, open-source and easily-revised e-commerce project.

But in default, it doesn't provide any kind free online space to store products' pictures. The offical documents describe how to use digitalOcean and AWS S3 to put your uploaded images of products but those services are used with paid.

Eventually, I found one way to use Imgur API to store our images for free totally. Following are the steps you can go with.

  1. create imgur account then go to its settings page. It will list client id and secrets key of apps as below capture.
    Image description
    If you don't have any apps yet, create one.
    Image description

  2. Declare the headers and create an promise image upload function to call imgur API(https://api.imgur.com/3/image). (request.js in src/services)

const headers = {
  "Content-Type": "multipart/form-data",
  Authorization: "Client-ID " + IMGUR_CLIENT_ID,
}
Enter fullscreen mode Exit fullscreen mode
export const imgurUploadPromise = (formData) => {
  const apiUrl = "https://api.imgur.com/3/image"
  return axios
    .post(apiUrl, formData, {
      headers,
    })
    .then((res) => {
      console.log(res)
      return res.data.data.link
    })
    .catch((err) => console.log(err))
}
Enter fullscreen mode Exit fullscreen mode

Make sure the link of response format should be res.data.data.link.

  1. Using promise.all to upload multiple images in one operation. (api.js in src/services)
  uploads: {
    create(files) {
      const promiseArray = []
      for (const f of files) {
        const formData = new FormData()
        formData.append("image", f)
        promiseArray.push(imgurUploadPromise(formData))
      }

      return Promise.all(promiseArray).then((values) => {
        const uploads = values.map((value) => {
          return { url: value }
        })
        return {
          data: {
            uploads,
          },
        }
      })
    },
Enter fullscreen mode Exit fullscreen mode

Remember the return data format must be { url: value } for each promise and return data: { uploads } for all.

Then it will be done successfully. (don't upload images each over than 5MB)
Image description

Top comments (0)