Image upload using Golang and React

Posted on

Golang is a blockbuster server side language in the field of efficiency and concurrency. If you are a Nodejs developer definitely you will come across express js for building your web api services. Gofiber is exactly like the express framework for golang and no doubt it booms with the efficiency of Fasthttp and golang.

In this blog post we will create a simple image upload server using gofiber and we will use reactjs for frontend to select image from file and upload to server.

we will use axios for http request to server and it is really awesome when we deal with implementing authentication and handling lots of api requests. It has lots of features which make life easy when dealing with api in react.

we will use chakra ui for designing material like button , images and layout it shins in Accessibility that directly effect better SEO.

library and tools we will use

  • golang
  • gofiber
  • reactjs
  • axios
  • chakra ui

Setup backend

create new directory and enter into it

mkdir go-react-image-upload

cd go-react-image-upload

Enter fullscreen mode

Exit fullscreen mode

create a new directory server inside go-react-image-upload and enter into it

mkdir server 

cd server

Enter fullscreen mode

Exit fullscreen mode

Setup go environment

go mod init

Enter fullscreen mode

Exit fullscreen mode

install packages required for backend

go get

go get

Enter fullscreen mode

Exit fullscreen mode

uuid will help to generate unique id so that we can name our image easily and no two image will have same name.

create new go file main.go inside server and start writting code

package main

import (


func main() {
    // create new fiber instance  and use across whole app
    app := fiber.New()

    // middleware to allow all clients to communicate using http and allow cors

    // serve  images from images directory prefixed with /images
    // i.e http://localhost:4000/images/someimage.webp

    app.Static("/images", "./images")

    // handle image uploading using post request

    app.Post("/", handleFileupload)

    // delete uploaded image by providing unique image name

    app.Delete("/:imageName", handleDeleteImage)

    // start dev server on port 4000


func handleFileupload(c *fiber.Ctx) error {

    // parse incomming image file

    file, err := c.FormFile("image")

    if err != nil {
        log.Println("image upload error --> ", err)
        return c.JSON(fiber.Map{"status": 500, "message": "Server error", "data": nil})


    // generate new uuid for image name 
    uniqueId := uuid.New()

    // remove "- from imageName"

    filename := strings.Replace(uniqueId.String(), "-", "", -1)

    // extract image extension from original file filename

    fileExt := strings.Split(file.Filename, ".")[1]

    // generate image from filename and extension
    image := fmt.Sprintf("%s.%s", filename, fileExt)

    // save image to ./images dir 
    err = c.SaveFile(file, fmt.Sprintf("./images/%s", image))

    if err != nil {
        log.Println("image save error --> ", err)
        return c.JSON(fiber.Map{"status": 500, "message": "Server error", "data": nil})

    // generate image url to serve to client using CDN

    imageUrl := fmt.Sprintf("http://localhost:4000/images/%s", image)

    // create meta data and send to client

    data := map[string]interface{}{

        "imageName": image,
        "imageUrl":  imageUrl,
        "header":    file.Header,
        "size":      file.Size,

    return c.JSON(fiber.Map{"status": 201, "message": "Image uploaded successfully", "data": data})

func handleDeleteImage(c *fiber.Ctx) error {
    // extract image name from params
    imageName := c.Params("imageName")

    // delete image from ./images
    err := os.Remove(fmt.Sprintf("./images/%s", imageName))
    if err != nil {
        return c.JSON(fiber.Map{"status": 500, "message": "Server Error", "data": nil})

    return c.JSON(fiber.Map{"status": 201, "message": "Image deleted successfully", "data": nil})

Enter fullscreen mode

Exit fullscreen mode

run main.go from server

go run main.go

Enter fullscreen mode

Exit fullscreen mode

Now our server is up and running we can test it using Postman


setup frontend

come outside from server directory and generate reactjs project using create-react-app

npx create-react-app reactjs

cd reactjs

Enter fullscreen mode

Exit fullscreen mode

install dependencies

npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4 axios

Enter fullscreen mode

Exit fullscreen mode


import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


  <App />

Enter fullscreen mode

Exit fullscreen mode

setup App.js

import { Box, ChakraProvider, Container } from "@chakra-ui/react";
import Axios from "axios";
import Upload from "./components/Upload";

Axios.defaults.baseURL = "http://localhost:4000";

function App() {
  return (
        <Container maxWidth="container.xl">
          <Upload />

export default App;

Enter fullscreen mode

Exit fullscreen mode

create new hook useUpload hook in hooks folder


import { useState } from "react";
import axios from "axios";
import { useToast } from "@chakra-ui/react";

const useUpload = () => {
const [image, setImage] = useState(null);
const [loading, setLoading] = useState(false);

const [uploadedImage, setUploadedImage] = useState(null);

const toast = useToast();

const handleChangeImage = (e) => {

const handleUploadImage = async () => {
try {
const formData = new FormData();
formData.append("image", image);
const res = await"/", formData);
if ( {
title: "Image Uploaded",
status: "success",
duration: 4000,
isClosable: true,

Leave a Reply

Your email address will not be published.