首頁  >  文章  >  後端開發  >  在 Go 中建立文件上傳 API

在 Go 中建立文件上傳 API

WBOY
WBOY原創
2024-09-05 12:30:39393瀏覽

Building a File Upload API in Go

建立文件上傳 API 是許多涉及使用者提交文件、圖像或其他媒體文件的 Web 應用程式的常見要求。在本文中,我們將指導您使用 Go 和 Gin 框架建立安全且有效率的文件上傳 API。您將學習如何設定項目、處理傳入檔案並安全地儲存它們,確保您的應用程式能夠可靠地管理使用者上傳的內容。

先決條件

去1.21

設定項目

設定 Go 專案依賴項。

go mod init app
go get github.com/gin-gonic/gin

專案結構

├─ main.go
├─ models
│  └─ product.go
└─ public
   └─ index.html

專案文件

產品.go

Product 是一個簡單的結構,用於在我們的檔案上傳 API 中測試檔案上傳。

package models

type Product struct {
    Name string
}

主機程式

此文件設定檔上傳 API。它將創建並設定最小的 Go Web 應用程式。

package main

import (
    "app/models"
    "io"
    "net/http"
    "os"
    "path/filepath"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
)

func main() {
    router := gin.Default()
    uploadPath := "./public/uploads"
    os.MkdirAll(uploadPath, os.ModePerm)
    router.Static("/uploads", uploadPath)
    router.StaticFile("/", "./public/index.html")
    router.POST("/submit", func(c *gin.Context) {
        var product models.Product
        if err := c.ShouldBindWith(&product, binding.FormMultipart); err != nil {
            c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())
            return
        }
        image, _ := c.FormFile("Image")
        filePath := filepath.Join(uploadPath, image.Filename)
        src, _ := image.Open()
        dst, _ := os.Create(filePath)
        io.Copy(dst, src)
        c.JSON(http.StatusOK, gin.H{"Name": product.Name, "Image": image.Filename})
    })
    router.Run()
}

  • 初始化 Gin 路由器並設定為上傳目錄和 index.html 提供靜態檔案服務。
  • 確保 ./public/uploads 目錄存在用於儲存上傳的檔案。
  • 在 /submit 定義一個 POST 路由來處理檔案上傳,將檔案儲存到伺服器,並傳回產品名稱和上傳的檔案名稱。
  • 啟動 Gin 伺服器來監聽傳入的請求。

索引.html

此 HTML 表單專為使用者上傳產品名稱以及關聯的圖片檔案而設計。

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
    <script>
        function submitForm() {
            let form = document.getElementById('form')
            let data = new FormData(form)
            fetch('submit', {
                method: 'POST',
                body: data
            }).then(res => {
                res.json().then(result => {
                    let alert = document.getElementById('alert')
                    alert.children[0].innerText = `Upload success!\nName: ${result.Name}\nImage: ${result.Image}`
                    alert.children[1].src = `/uploads/${result.Image}`
                    alert.classList.remove('d-none')
                    form.reset()
                })
            })
            return false
        }
    </script>
</head>
<body>
    <div class="container">
        <div class="row mt-3">
            <form id="form" onsubmit="return submitForm()">
                <div class="mb-3 col-12">
                    <label class="form-label" for="name">Name</label>
                    <input id="name" name="Name" class="form-control form-control-sm" required />
                </div>
                <div class="mb-3 col-12">
                    <label class="form-label" for="image">Image</label>
                    <input type="file" accept="image/*" id="image" name="Image" class="form-control form-control-sm" required />
                </div>
                </div>
                <div class="col-12">
                    <button class="btn btn-sm btn-primary">Submit</button>
                </div>
            </form>
            <div id="alert" class="alert alert-success mt-3 d-none">
                <p></p>
                <img id="img" width="200px" />
            </div>
        </div>
    </div>
</body>
</html>

表單設定為透過JavaScript函數submitForm()提交,該函數在表單提交時觸發。另外,還有一個隱藏的提醒部分,可以顯示上傳的圖片以及提交成功後的成功訊息。

運行專案

go run main.go

開啟網頁瀏覽器並前往http://localhost:8080

你會發現這個測試頁。

Building a File Upload API in Go

測試

在輸入欄位中輸入名稱並瀏覽要上傳的檔案。

Building a File Upload API in Go

點選提交按鈕發送表單。然後,您將看到一條成功訊息以及從我們的 API 返回的已提交資訊。

Building a File Upload API in Go

本質上,Go 與 Gin 框架簡化了 Web 應用程式中檔案上傳的管理。透過使用簡單的處理程序和表單設置,您可以有效地處理文件上傳並改善專案中的使用者體驗。

原始碼:https://github.com/stackpuz/Example-File-Upload-Go

在幾分鐘內建立一個 CRUD Web 應用程式:https://stackpuz.com

以上是在 Go 中建立文件上傳 API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn