>  기사  >  백엔드 개발  >  Go에서 파일 업로드 API 구축

Go에서 파일 업로드 API 구축

WBOY
WBOY원래의
2024-09-05 12:30:39393검색

Building a File Upload API in Go

파일 업로드 API를 생성하는 것은 사용자가 문서, 이미지 또는 기타 미디어 파일을 제출하는 것과 관련된 많은 웹 애플리케이션의 일반적인 요구 사항입니다. 이 기사에서는 Gin 프레임워크와 함께 Go를 사용하여 안전하고 효율적인 파일 업로드 API를 구축하는 방법을 안내합니다. 프로젝트를 설정하고, 들어오는 파일을 처리하고, 안전하게 저장하여 애플리케이션이 사용자가 업로드한 콘텐츠를 안정적으로 관리할 수 있도록 하는 방법을 배우게 됩니다.

전제 조건

1.21로 이동

프로젝트 설정

Go 프로젝트 종속성을 설정합니다.

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

프로젝트 구조

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

프로젝트 파일

product.go

제품은 파일 업로드 API에서 파일 업로드를 테스트하는 데 사용되는 간단한 구조체입니다.

package models

type Product struct {
    Name string
}

main.go

파일 업로드 API를 설정하는 파일입니다. 최소한의 Go 웹 애플리케이션을 생성하고 설정합니다.

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 서버를 시작합니다.

index.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 with the Gin 프레임워크는 웹 애플리케이션에서 파일 업로드 관리를 간소화합니다. 간단한 처리기와 양식 설정을 사용하면 파일 업로드를 효율적으로 처리하고 프로젝트의 사용자 경험을 향상시킬 수 있습니다.

소스 코드: https://github.com/stackpuz/Example-File-Upload-Go

몇 분 만에 CRUD 웹 앱 만들기: https://stackpuz.com

위 내용은 Go에서 파일 업로드 API 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.