golang simply gets the implementation code to upload the file size

  • 2020-06-01 09:59:30
  • OfStack

This example shows how golang can simply get the size of an uploaded file. I will share it with you for your reference as follows:

package main
import (
    "fmt"
    "io"
    "net/http"
    "log"
    "os"
)
// Gets the interface for the file size
type Size interface {
    Size() int64
}
// Interface to get file information
type Stat interface {
    Stat() (os.FileInfo, error)
}
// hello world, the web server
func HelloServer(w http.ResponseWriter, r *http.Request) {
    if "POST" == r.Method {
        file, _, err := r.FormFile("userfile")
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }
        if statInterface, ok := file.(Stat); ok {
            fileInfo, _ := statInterface.Stat()
            fmt.Fprintf(w, " The size of the uploaded file is : %d", fileInfo.Size())
        }
        if sizeInterface, ok := file.(Size); ok {
            fmt.Fprintf(w, " The size of the uploaded file is : %d", sizeInterface.Size())
        }
        return
    }
    // The upload page
    w.Header().Add("Content-Type", "text/html")
    w.WriteHeader(200)
    html := `
<form enctype="multipart/form-data" action="/hello" method="POST">
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
`
    io.WriteString(w, html)
}
func main() {
    http.HandleFunc("/hello", HelloServer)
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

I hope this article has been helpful to you in programming Go.


Related articles: