Golang How HTTP client uploads and how server receives files

Source: Internet
Author: User

Given an example, use Mime/multipart to implement how the client uploads a file to the server, and then how the server accepts the file.

See Server.go Code

package mainimport (    "io"    "os"    "fmt"    "io/ioutil"    "net/http")func uploadHandler(w http.ResponseWriter, r *http.Request) {    reader, err := r.MultipartReader()    if err != nil {        http.Error(w, err.Error(), http.StatusInternalServerError)        return    }    for {        part, err := reader.NextPart()        if err == io.EOF {            break        }        fmt.Printf("FileName=[%s], FormName=[%s]\n", part.FileName(), part.FormName())        if part.FileName() == "" {  // this is FormData            data, _ := ioutil.ReadAll(part)            fmt.Printf("FormData=[%s]\n", string(data))        } else {    // This is FileData            dst, _ := os.Create("./" + part.FileName() + ".upload")            defer dst.Close()            io.Copy(dst, part)        }    }}func main() {    http.HandleFunc("/upload", uploadHandler)    http.ListenAndServe(":8080", nil)}

Example 1:client uploading a file

package mainimport (    "io"    "os"    "log"    "bytes"    "io/ioutil"    "net/http"    "mime/multipart")func main() {    bodyBuffer := &bytes.Buffer{}    bodyWriter := multipart.NewWriter(bodyBuffer)    fileWriter, _ := bodyWriter.CreateFormFile("files", "file.txt")    file, _ := os.Open("file.txt")    defer file.Close()    io.Copy(fileWriter, file)    contentType := bodyWriter.FormDataContentType()    bodyWriter.Close()    resp, _ := http.Post("http://localhost:8080/upload", contentType, bodyBuffer)    defer resp.Body.Close()    resp_body, _ := ioutil.ReadAll(resp.Body)    log.Println(resp.Status)    log.Println(string(resp_body))}

Example 2:client uploading multiple files

package mainimport (    "io"    "os"    "log"    "bytes"    "io/ioutil"    "net/http"    "mime/multipart")func main() {    bodyBuffer := &bytes.Buffer{}    bodyWriter := multipart.NewWriter(bodyBuffer)    // file1    fileWriter1, _ := bodyWriter.CreateFormFile("files", "file1.txt")    file1, _ := os.Open("file1.txt")    defer file1.Close()    io.Copy(fileWriter1, file1)    // file2    fileWriter2, _ := bodyWriter.CreateFormFile("files", "file2.txt")    file2, _ := os.Open("file2.txt")    defer file2.Close()    io.Copy(fileWriter2, file2)    contentType := bodyWriter.FormDataContentType()    bodyWriter.Close()    resp, _ := http.Post("http://localhost:8080/upload", contentType, bodyBuffer)    defer resp.Body.Close()    resp_body, _ := ioutil.ReadAll(resp.Body)    log.Println(resp.Status)    log.Println(string(resp_body))}

Example 3: Uploading other form data

Package Mainimport ("IO" "OS" "Log" "bytes" "Io/ioutil" "Net/http" "Mime/multipart") func main () { Bodybuffer: = &bytes. buffer{} bodywriter: = multipart. Newwriter (Bodybuffer)//File1 FileWriter1, _: = Bodywriter.createformfile ("Files", "File1.txt") file1, _: = OS.O Pen ("file1.txt") defer file1. Close () Io. Copy (FileWriter1, file1)//File2 FileWriter2, _: = Bodywriter.createformfile ("Files", "File2.txt") file2, _: = O S.open ("File2.txt") defer file2. Close () Io.        Copy (FileWriter2, file2)//Other form data extraparams: = map[string]string{"title": "My Document",    "Author": "Matt Aimonetti", "description": "A document with all the Go programming language Secrets", } for key, value: = Range Extraparams {_ = Bodywriter.writefield (key, Value)} ContentType: = Bodywriter . Formdatacontenttype () Bodywriter.close () resp, _: = http. Post ("Http://localhost:8080/upload", ContenttypE, Bodybuffer) defer resp. Body.close () Resp_body, _: = Ioutil. ReadAll (resp. Body) log. Println (resp. Status) log. Println (String (resp_body))}

Look at the server side of the run output:

$ go build server.go && ./serverFileName=[file1.txt], FormName=[files]FileName=[file2.txt], FormName=[files]FileName=[], FormName=[description]FormData=[A document with all the Go programming language secrets]FileName=[], FormName=[title]FormData=[My Document]FileName=[], FormName=[author]FormData=[Matt Aimonetti]$ ls -ltotal 25180-rwxr-xr-x 1 ... 6179399 Jun 22 08:07 client-rw-r--r-- 1 ...    1952 Jun 22 08:06 client.go-rw-r--r-- 1 ...      15 Jun 22 07:11 file1.txt-rw-r--r-- 1 ...      15 Jun 22 08:28 file1.txt.upload-rw-r--r-- 1 ...      14 Jun 22 07:11 file2.txt-rw-r--r-- 1 ...      14 Jun 22 08:28 file2.txt.upload-rw-r--r-- 1 ...      15 Jun 22 07:56 file.txt-rw-r--r-- 1 ...      15 Jun 22 08:10 file.txt.upload-rwxr-xr-x 1 ... 6717437 Jun 22 07:59 server-rw-r--r-- 1 ...    1580 Jun 22 07:58 server.go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.