简体   繁体   中英

how to get file name of multipart-form file in go?

I am trying to upload a multipart form which has a file along with some other data. I know the tag name for the file using which I do FormFile but I want to get the name of the file also. I am not able to figure out how to do this?

Given a simple form like this in a file called form.html :

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>File Upload example</title>
</head>

<body>
    <form action="/form-endpoint" method="post" enctype="multipart/form-data">
        <label for="file-input">Choose an image</label>
        <input type="file" id="file-input" name="file-input" accept="image/png, image/jpeg">
        <input type="submit" value="Submit">
    </form>
</body>

</html>

I can get the file name of the uploaded file using the POST request's *multipart.Reader struct like so in a file called main.go :

package main

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

func serveForm(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "form.html")
}

func handleFormSubmit(w http.ResponseWriter, r *http.Request) {
    reader, err := r.MultipartReader()
    if err != nil {
        log.Fatalf("failed to create multipart-reader: %s", err)
    }

    for p, err := reader.NextPart(); err != io.EOF; p, err = reader.NextPart() {
        log.Println(p.FileName())  // This line in particular is what you're looking for.
    }
}

func main() {
    http.HandleFunc("/", serveForm)
    http.HandleFunc("/form-endpoint", handleFormSubmit)
    if err := http.ListenAndServe(":8000", nil); err != nil {
        log.Fatalf("failed to start server: %s", err)
    }
}

This is a good starting point in the docs to learn more about multipart/form-data reading: https://golang.org/pkg/net/http/#Request.MultipartReader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM