Static files

Create Assets folder in the project directory and put some images like the following

root@ubuntu:/ SuperxonWebsite. ├── assets ├─ golang.jpeg │ ├─ favicon. Ico │ ├─ img │ ├─ web mian.goCopy the code

Static files are static resources on the server, such as audio, images, text, scripts, etc. To make static files directly accessible to users, Gin framework has three functions implemented:

package main

import (
   "github.com/gin-gonic/gin"
)

func main(a) {
   r := gin.Default()
   
   / / 1.
   r.Static("/assets"."./assets") 
   / / 2.
   //r.StaticFS("/assets", http.Dir("assets")) 
   / / 3.
   r.StaticFile("/favicon.ico"."./assets/favicon.ico")
   
   r.Run(": 8080")}Copy the code

(1). Access tohttp://localhost:8080/assets/golang.jpeg, you can access golang.jpeg; It can be used to access all the files under assets.

②. The function is similar to ①, but there is a special function is accesshttp://localhost:8080/assets/img/, can directly display all files under IMG;

(3). Access tohttp://localhost:8080/favicon.ico, can directly access the corresponding files,

2. Upload files

Uploading a single file

package main

import (
   "fmt"
   "github.com/gin-gonic/gin"
   "net/http"
)

func main(a) {
   r := gin.Default()
   r.POST("/upload_one".func(c *gin.Context) {
      file, err := c.FormFile("test_file")
      iferr ! =nil {
         c.JSON(http.StatusInternalServerError, gin.H{
            "message": err.Error(),
         })
         return
      }

      fmt.Println(file.Filename)
      // Upload the file to the specified directory
      _ = c.SaveUploadedFile(file, "./assets/"+file.Filename)
      c.JSON(http.StatusOK, gin.H{
         "message": fmt.Sprintf("'%s' upload success.", file.Filename),
      })
   })
   _ = r.Run(": 8080")}Copy the code

Uploading files for testing can passpostmanAfter success, you can see that there are many uploaded files in the assets folder

Uploading multiple files

Similar to a single file, withMultipartFormI’m going to do it ahead of time,postmanTo select multiple files

func main(a) {
   r := gin.Default()
   r.POST("/upload_files".func(c *gin.Context) {
      // Single file
      form, _ := c.MultipartForm()
      files := form.File["test_files"]

      for _, file := range files {
         // Upload the file to the specified directory
         _ = c.SaveUploadedFile(file, "./assets/"+ file.Filename)
      }

      c.JSON(http.StatusOK, gin.H{
         "message": fmt.Sprintf("files upload success."),
      })
   })
   _ = r.Run(": 8080")}Copy the code