[ginを使った画像アップロード処理] サムネイルを作成して指定パスに画像を保存します。 #image
package main
import (
"crypto/sha1"
"fmt"
"path/filepath"
"time"
"github.com/gin-gonic/gin"
imgupload "github.com/olahol/go-imageupload"
)
func main() {
// Upload先のディレクトリ
dstDir := "./public/uploads"
router := gin.Default()
router.MaxMultipartMemory = 8 << 20
router.Static("/", "./views")
router.POST("/upload", func(c *gin.Context) {
img, err := imgupload.Process(c.Request, "file")
if err != nil {
panic(err)
}
thumb, err := imgupload.ThumbnailJPEG(img, 300, 300, 90)
if err != nil {
panic(err)
}
h := sha1.Sum(thumb.Data)
savepath := filepath.Join(dstDir, fmt.Sprintf("%s_%x.jpg", time.Now().Format("20060102150405"), h[:4]))
thumb.Save(savepath)
})
router.Run(":5000")
}
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Multiple file upload</title>
<link rel="stylesheet" type="text/css" href="./css/dropzone.css">
<link rel="stylesheet" type="text/css" href="./css/fa-svg-with-js.css">
<script type="text/javascript" src="./js/dropzone.js"></script>
<script type="text/javascript" src="./js/fontawesome-all.min.js"></script>
</head>
<body>
<div id="dropzone">
<form action="/upload" class="dropzone needsclick dz-clickable" id="file-upload">
<div class="dz-message needsclick">
<i class="far fa-file-image"></i> Drop files here or click to upload.
</div>
</form>
</div>
</body>
</html>