LoginSignup
2
2
Qiita×Findy記事投稿キャンペーン 「自分のエンジニアとしてのキャリアを振り返ろう!」

【Go/Gin】画像をアップロードしてディレクトリ内に保存する

Posted at

やりたいこと

画像をGinのAPIサーバーへアップロードし./imagesディレクトリに保存したい。

実装方法

main.go
package main

import (
	"net/http"
	"path/filepath"

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

func main() {
	router := gin.Default()
	router.MaxMultipartMemory = 8 << 20

	router.POST("/images", func(c *gin.Context) {
		file, err := c.FormFile("images")
		if err != nil {
			c.String(http.StatusBadRequest, "get form err: %s", err.Error())
			return
		}

		savepath := filepath.Join("images", file.Filename)
		if err := c.SaveUploadedFile(file, savepath); err != nil {
			c.String(http.StatusBadRequest, "upload file err: %s", err.Error())
			return
		}

		c.String(http.StatusOK, "File %s uploaded successfully.", file.Filename)
	})

	router.Run(":8080")
}

アップロード用のディレクトリを作成しておく

今回は./imagesに保存します。

スクリーンショット 2024-02-01 17.02.39.png

path/filepathを使う

os間の物理ファイルパスのセパレータがUNIX系は/で、Windows系は\のように異なるので、その差異を吸収してくれるようによしなに扱ってくれるライブラリ。

動作確認

Postmanで確認

スクリーンショット 2024-02-01 17.04.34.png

form-dataにアップロードしたい画像ファイルを添付し、POSTする。
keyはfile, err := c.FormFile("image")の部分で指定したimageに合わせる。

スクリーンショット 2024-02-01 17.06.21.png

無事アップロード完了。

サーバーサイドで確認

スクリーンショット 2024-02-01 17.07.26.png

しっかり指定したディレクトリに画像がアップロードされていることを確認。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2