POST data using the Content-Type multipart/form-data

后端 未结 7 1392
小鲜肉
小鲜肉 2020-11-27 12:16

I\'m trying to upload images from my computer to a website using go. Usually, I use a bash script that sends a file and a key to the server:

curl -F \"image         


        
相关标签:
7条回答
  • 2020-11-27 13:20

    I have found this tutorial very helpful to clarify my confusions about file uploading in Go.

    Basically you upload the file via ajax using form-data on a client and use the following small snippet of Go code on the server:

    file, handler, err := r.FormFile("img") // img is the key of the form-data
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    
    fmt.Println("File is good")
    fmt.Println(handler.Filename)
    fmt.Println()
    fmt.Println(handler.Header)
    
    
    f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    io.Copy(f, file)
    

    Here r is *http.Request. P.S. this just stores the file in the same folder and does not perform any security checks.

    0 讨论(0)
提交回复
热议问题