golang multipart/form-data POST上传文件

前端之家收集整理的这篇文章主要介绍了golang multipart/form-data POST上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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
}
@H_301_2@ 如果要指定上传的每个部分的Content-Type,则需要重写multipart.WriterCreateFormFieldCreateFormFile方法

@H_301_2@

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)
}
原文链接:https://www.f2er.com/go/190035.html

猜你在找的Go相关文章