GO language to achieve file upload code sharing

  • 2020-05-30 20:19:38
  • OfStack

The functionality is simple, the code is simple, and there's no more crap here.


package main
import (
    "fmt"
    "io"
    "net/http"
    "os"
)
const (
    upload_path string = "./upload/"
)
func helloHandle(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "hello world!")
}
// upload
func uploadHandle(w http.ResponseWriter, r *http.Request) {
    // Determine the method from the request
    if r.Method == "GET" {
        io.WriteString(w, "<html><head><title> My first 1 A page </title></head><body><form action='' method=\"post\" enctype=\"multipart/form-data\"><label> To upload pictures </label><input type=\"file\" name='file'  /><br/><label><input type=\"submit\" value=\" To upload pictures \"/></label></form></body></html>")
    } else {
        // Get file content To get it like this
        file, head, err := r.FormFile("file")
        if err != nil {
            fmt.Println(err)
            return
        }
        defer file.Close()
        // Create a file
        fW, err := os.Create(upload_path + head.Filename)
        if err != nil {
            fmt.Println(" File creation failed ")
            return
        }
        defer fW.Close()
        _, err = io.Copy(fW, file)
        if err != nil {
            fmt.Println(" File save failed ")
            return
        }
        //io.WriteString(w, head.Filename+" Save success ")
        http.Redirect(w, r, "/hello", http.StatusFound)
        //io.WriteString(w, head.Filename)
    }
}
func main() {
    // Start the 1 a http The server
    http.HandleFunc("/hello", helloHandle)
    // upload
    http.HandleFunc("/image", uploadHandle)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(" Server startup failed ")
        return
    }
    fmt.Println(" Server started successfully ")
}

The above is the content of this article, hope you can enjoy it, can help you learn go language.


Related articles: