1. 程式人生 > 其它 >Golang模擬客戶端POST表單功能檔案上傳

Golang模擬客戶端POST表單功能檔案上傳

技術標籤:gogolanggogolang

package main
 
import (
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "mime/multipart"
    "net/http"
    "os"
)
 
func postFile(filename string, targetUrl string) error {
    bodyBuf := &bytes.Buffer{}
    bodyWriter := multipart.NewWriter(bodyBuf)
 
    //關鍵的一步操作
    fileWriter, err := bodyWriter.CreateFormFile("uploadfile", filename)
    if err != nil {
        fmt.Println("error writing to buffer")
        return err
    }
 
    //開啟檔案控制代碼操作
    fh, err := os.Open(filename)
    if err != nil {
        fmt.Println("error opening file")
        return err
    }
    defer fh.Close()
 
    //iocopy
    _, err = io.Copy(fileWriter, fh)
    if err != nil {
        return err
    }
 	//新增其他引數
	//param := map[string]string{}
	//if len(param) != 0 {
	//	//param是一個一維的map結構
	//	for k, v := range param {
	//		bodyWriter.WriteField(k, v)
	//	}
	//}
    contentType := bodyWriter.FormDataContentType()
    bodyWriter.Close()
 
    resp, err := http.Post(targetUrl, contentType, bodyBuf)
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    resp_body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return err
    }
    fmt.Println(resp.Status)
    fmt.Println(string(resp_body))
    return nil
}
 
// sample usage
func main() {
    target_url := "http://localhost/upload"
    filename := "./example.pdf"
    postFile(filename, target_url)
}

本文連線:https://www.cnblogs.com/Akkuman/p/golang-upload-file-with-httppost.html