go使用mime/multipart包案例

1.multipart实现了MIME的multipart解析,参见RFC 2046。该实现适用于HTTP(RFC 2388)和常见浏览器生成的multipart主体,个人理解期本质就是默认from在网络中传输格式

案例一:普通普通表单上传后端程序

func main() {
	buf:=new(bytes.Buffer)
	bodywriter:=multipart.NewWriter(buf)
	bodywriter.WriteField("name","lisi")
	bodywriter.WriteField("age","40")
	contentType:=bodywriter.FormDataContentType()
	defer bodywriter.Close()
	url:="http://www.shop.com:8088/index/index/aa"
	http.Post(url,contentType,buf)
}

案例二:带文件上传的表单上传

func main(){
	bodybuf:=new(bytes.Buffer)
	boderwriter:=multipart.NewWriter(bodybuf)
	boderwriter.WriteField("name","lisi")
	testFile:="./1.jpg"
	formfile,_:=boderwriter.CreateFormFile("file","5.jpg")
	srcFile,_:=os.Open(testFile)
	defer srcFile.Close()
	io.Copy(formfile,srcFile)
	contentType:=boderwriter.FormDataContentType()
	url:="http://www.shop.com:8088/index/index/aa"
	boderwriter.Close()
	re,_:=http.Post(url,contentType,bodybuf)
	fmt.Println(re)
}

  

仅供参考

原文地址:https://www.cnblogs.com/zh718594493/p/15324235.html