gin框架上传文件到minio

package main

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

// Declare MinIO client variable and error outside of main()
var minioClient *minio.Client
var err error

func main() {
	// Set up MinIO client (moved inside main function)
	minioClient, err = minio.New("192.168.2.110:58894", &minio.Options{
		Creds:  credentials.NewStaticV4("admins", "123qweasd", ""),
		Secure: false,
	})
	if err != nil {
		log.Fatalln(err)
	}

	// Set up Gin router
	r := gin.Default()

	// Serve upload page
	r.LoadHTMLFiles("index.html")
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	// Handle form submission
	r.POST("/upload", func(c *gin.Context) {
		// Parse form data
		file, header, err := c.Request.FormFile("file")
		if err != nil {
			c.AbortWithError(http.StatusBadRequest, err)
			return
		}
		defer file.Close()

		// Read file contents
		data, err := ioutil.ReadAll(file)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		// Upload file to MinIO
		_, err = minioClient.PutObject(
			context.Background(),
			"写你的桶",
			header.Filename,
			bytes.NewBuffer(data),
			int64(len(data)),
			minio.PutObjectOptions{},
		)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		// Show success message
		c.String(http.StatusOK, "File uploaded successfully!")
	})

	// Start server
	port := 8080
	log.Printf("Listening on port %d...\n", port)
	log.Fatal(r.Run(fmt.Sprintf(":%d", port)))
}

DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Upload file to MinIOtitle>
head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <br />
        <br />
        <button type="submit">Uploadbutton>
    form>
body>
html>

gin框架上传文件到minio_第1张图片

gin框架上传文件到minio_第2张图片

你可能感兴趣的:(GO,golang,开发语言,后端)