2

I am using Golang(gin-gonic framework) for my backend. I have developed below rest API to receive images or files from the frontend applications. I am saving files in this path "/home/user/Desktop/files/"+dt.String()+"_"+filepath.Base(file.Filename). Till now everything fine, I can see the saved files.

Now I am planning to return these file paths to frontend via another rest API (Eg: API: /getImageUrl, Response: https://via.placeholder.com/600/771796) so that users can download files. But I am not sure how to return these file path URLs to frontend. Can somebody guide me on how to develop this rest API?

               requests.POST("/upload", func(c *gin.Context) {

                    // Source
                    file, err := c.FormFile("file")
                    if err != nil {
                        c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
                        return
                    }

                    dt := time.Now()

                    filename := "/home/user/Desktop/files/"+dt.String()+"_"+filepath.Base(file.Filename)

                    if err := c.SaveUploadedFile(file, filename); err != nil {
                        c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
                        return
                    }

                    c.JSON(200, gin.H{"message": "Files Uploaded Successfully"})
                }) 
TylerH
  • 20,799
  • 66
  • 75
  • 101
Cherry
  • 699
  • 1
  • 7
  • 20

1 Answers1

2

First, you should store the image name in the database.

To serve the static assets (image file) in gin you have to define a static route.

router := gin.Default()
router.Static("/image", "./path-to-image-dir")

file path will look something like that

http://myapp.com/image/filename.jpg

but i will recommend you to use a custom header for serving images content using bind-header method that way you will have more control. you can read more about it in the gin documentation.

https://github.com/gin-gonic/gin#bind-header

Akshay Deep Giri
  • 3,139
  • 5
  • 25
  • 33