建立文件上傳 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 表單專為使用者上傳產品名稱以及關聯的圖片檔案而設計。
<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> <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> </form> </div> <div class="col-12"> <button class="btn btn-sm btn-primary">Submit</button> </div> <div id="alert" class="alert alert-success mt-3 d-none"> <p></p> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172551064373054.jpg?x-oss-process=image/resize,p_40" class="lazy" id="img" style="max-width:90%" alt="在 Go 中建立文件上傳 API" > </div> </div>
以上是在 Go 中建立文件上傳 API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文解釋了GO的軟件包導入機制:命名imports(例如導入“ fmt”)和空白導入(例如導入_ fmt; fmt;)。 命名導入使包裝內容可訪問,而空白導入僅執行t

本文解釋了Beego的NewFlash()函數,用於Web應用程序中的頁間數據傳輸。 它專注於使用newflash()在控制器之間顯示臨時消息(成功,錯誤,警告),並利用會話機制。 Lima

本文詳細介紹了MySQL查詢結果的有效轉換為GO結構切片。 它強調使用數據庫/SQL的掃描方法來最佳性能,避免手動解析。 使用DB標籤和Robus的結構現場映射的最佳實踐

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

本文詳細介紹了在GO中詳細介紹有效的文件,將OS.WriteFile(適用於小文件)與OS.openfile和緩衝寫入(最佳大型文件)進行比較。 它強調了使用延遲並檢查特定錯誤的可靠錯誤處理。

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6
視覺化網頁開發工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中