go post 上傳檔案的例子

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
go post 上傳檔案
package mainimport (    "bytes"    "fmt"    "io"    "mime/multipart"    "net/http"    "os")func postFile(filename string, target_url string) (*http.Response, error) {    body_buf := bytes.NewBufferString("")    body_writer := multipart.NewWriter(body_buf)    // use the body_writer to write the Part headers to the buffer    _, err := body_writer.CreateFormFile("userfile", filename)    if err != nil {        fmt.Println("error writing to buffer")        return nil, err    }    // the file data will be the second part of the body    fh, err := os.Open(filename)    if err != nil {        fmt.Println("error opening file")        return nil, err    }    // need to know the boundary to properly close the part myself.    boundary := body_writer.Boundary()    //close_string := fmt.Sprintf("\r\n--%s--\r\n", boundary)    close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))    // use multi-reader to defer the reading of the file data until    // writing to the socket buffer.    request_reader := io.MultiReader(body_buf, fh, close_buf)    fi, err := fh.Stat()    if err != nil {        fmt.Printf("Error Stating file: %s", filename)        return nil, err    }    req, err := http.NewRequest("POST", target_url, request_reader)    if err != nil {        return nil, err    }    // Set headers for multipart, and Content Length    req.Header.Add("Content-Type", "multipart/form-data; boundary="+boundary)    req.ContentLength = fi.Size() + int64(body_buf.Len()) + int64(close_buf.Len())    return http.DefaultClient.Do(req)}// sample usagefunc main() {    target_url := "http://localhost:8086/upload"    filename := "/Users/wei/Downloads/21dian_1.9_10"    postFile(filename, target_url)}參考文章 https://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/ 25package mainimport (    "bytes"    "fmt"    "log"    "mime/multipart"    "net/http")// Creates a new file upload http request with optional extra paramsfunc newMultipartRequest(url string, params map[string]string) (*http.Request, error) {    body := &bytes.Buffer{}    writer := multipart.NewWriter(body)    for key, val := range params {        _ = writer.WriteField(key, val)    }    writer.Close()    return http.NewRequest("POST", url, body)}func main() {    extraParams := map[string]string{        "title":       "My Document",        "author":      "zieckey",        "description": "A document with all the Go programming language secrets",    }    request, err := newMultipartRequest("http://127.0.0.1:8091/echo", extraParams)    if err != nil {        log.Fatal(err)    }    client := &http.Client{}    resp, err := client.Do(request)    if err != nil {        log.Fatal(err)    } else {        body := &bytes.Buffer{}        _, err := body.ReadFrom(resp.Body)        if err != nil {            log.Fatal(err)        }        resp.Body.Close()        fmt.Println(resp.StatusCode)        fmt.Println(resp.Header)        fmt.Println(body)    }}multipart 的例子package mainimport (    "bytes"    "fmt"    "io"    "log"    "mime/multipart"    "net/http"    "os"    "path/filepath")// Creates a new file upload http request with optional extra paramsfunc newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {    file, err := os.Open(path)    if err != nil {        return nil, err    }    defer file.Close()    body := &bytes.Buffer{}    writer := multipart.NewWriter(body)    part, err := writer.CreateFormFile(paramName, filepath.Base(path))    if err != nil {        return nil, err    }    _, err = io.Copy(part, file)    for key, val := range params {        _ = writer.WriteField(key, val)    }    err = writer.Close()    if err != nil {        return nil, err    }    request, err := http.NewRequest("POST", uri, body)    request.Header.Add("Content-Type", writer.FormDataContentType())    return request, err}func main() {    path, _ := os.Getwd()    path += "/test.pdf"    extraParams := map[string]string{        "title":       "My Document",        "author":      "Matt Aimonetti",        "description": "A document with all the Go programming language secrets",    }    request, err := newfileUploadRequest("http://localhost:8086/upload", extraParams, "userfile", "/Users/wei/Downloads/21dian_1.9_10")    if err != nil {        log.Fatal(err)    }    client := &http.Client{}    resp, err := client.Do(request)    if err != nil {        log.Fatal(err)    } else {        body := &bytes.Buffer{}        _, err := body.ReadFrom(resp.Body)        if err != nil {            log.Fatal(err)        }        resp.Body.Close()        fmt.Println(resp.StatusCode)        fmt.Println(resp.Header)        fmt.Println(body)    }}

閱讀原文

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.