运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

golang multipart/form-data POST上传文件

运维开发网 https://www.qedev.com 2020-04-01 17:23 出处:网络 作者:运维开发网整理
package main import ( "bytes" "errors" "fmt" "io/ioutil" "mime/multipart" "net/http" ) func main() { createMemoToAmazon() } func createMemoToAmazon() error { buf := new(bytes.Buffer) w :=
package main

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
)

func main() {
	createMemoToAmazon()
}

func createMemoToAmazon() error {
	buf := new(bytes.Buffer)
	w := multipart.NewWriter(buf)

	err := w.WriteField("comment", "我的世界!!!")
	if err != nil {
		fmt.Println(err)
		return err
	}

	resp, err := http.Get("http://www.xxx.com/1d595495-0580-49ec-b96c-cc3346096718")
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("resp status:" + fmt.Sprint(resp.StatusCode))
	}

	bin, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return err
	}

	fw, err := w.CreateFormFile("file", "1d595495-0580-49ec-b96c-cc3346096718")
	if err != nil {
		fmt.Println(err)
		return err
	}

	_, err = fw.Write(bin)
	if err != nil {
		fmt.Println(err)
		return err
	}
	w.Close()


	req, err := http.NewRequest("POST", "http://localhost:8080/info", buf)
	if err != nil {
		fmt.Println("req err: ", err)
		return err
	}
	req.Header.Set("Content-Type", w.FormDataContentType())

	resp, err = http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println("resp err: ", err)
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return errors.New("resp status:" + fmt.Sprint(resp.StatusCode))
	}

	return nil
}

如果要指定上传的每个部分的Content-Type,则需要重写multipart.Writer的CreateFormField和CreateFormFile方法

func CreateFormFile(fieldname, filename, contentType string, w *multipart.Writer) (io.Writer, error) {
	h := make(textproto.MIMEHeader)
	h.Set("Content-Disposition",
		fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
			escapeQuotes(fieldname), escapeQuotes(filename)))
	h.Set("Content-Type", contentType)
	return w.CreatePart(h)
}

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消