backend (Go) 개발

http fileupload

꼰대코더 2025. 3. 8. 01:43

Client html for uploading file

<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
</head>
<body>
    <form
       enctype="multipart/form-data"
        action="http://localhost:8080/upload"
        method="post"
    >
   <input type="file" name="myFile" />
    <input type="submit" value="upload" />
</form>
</body>
</html>

 

Server

package main

import (
        "fmt"
        "io"
        "log"
        "net/http"
        "os"
)

func uploadFile(w http.ResponseWriter, r *http.Request) {
    fmt.Println("File Upload Endpoint Hit")

    // Parse our multipart form, 10 << 20 specifies a maximum
    // upload of 10 MB files.
    r.ParseMultipartForm(10 << 20)
    // FormFile returns the first file for the given key `myFile`
    // it also returns the FileHeader so we can get the Filename,
    // the Header and the size of the file
    file, handler, err := r.FormFile("myFile")
    if err != nil {
        fmt.Println("Error Retrieving the File")
        fmt.Println(err)
        return
    }
    defer file.Close()
    fmt.Printf("Uploaded File: %+v\n", handler.Filename)
    fmt.Printf("File Size: %+v\n", handler.Size)
    fmt.Printf("MIME Header: %+v\n", handler.Header)

    // Create a temporary file within our temp-images directory that follows
    // a particular naming pattern
    tempFile, err := os.CreateTemp("temp-images", "upload-*.jpg")
    if err != nil {
        fmt.Println(err)
    }
    defer tempFile.Close()

    // read all of the contents of our uploaded file into a
    // byte array
    fileBytes, err := io.ReadAll(file)
    if err != nil {
        fmt.Println(err)
    }
    // write this byte array to our temporary file
    tempFile.Write(fileBytes)
    // return that we have successfully uploaded our file!
    fmt.Fprintf(w, "Successfully Uploaded File\n")
}

func sayHello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there!")
}

func setupHandler(mux *http.ServeMux) {
    mux.HandleFunc("/", sayHello)
    mux.HandleFunc("/upload", uploadFile)
}

func main() {
    listenAddr := os.Getenv("LISTEN_ADDR")
    if len(listenAddr) == 0 {
        listenAddr = ":8080"
    }

    mux := http.NewServeMux()
    setupHandler(mux)
    log.Fatal(http.ListenAndServe(listenAddr, mux))
}

'backend (Go) 개발' 카테고리의 다른 글

http parseQuery  (0) 2025.03.08
http JSON  (0) 2025.03.08
Build HTTP Server  (0) 2025.03.05
환경설정  (0) 2025.03.04