前言
用到这个主要是做图片上传, python的好写, go的找各种文档真的挺费劲的…
Python
# 获取字节流 with open("/Users/xiaofei/Downloads/ywdhzxf.jpg", "rb") as f: res = f.read() print(res) # 发送请求 resp = requests.post(url='http://127.0.0.1/pic/upload', files={'file_stream': res}, data={'route_str': 'xiaofei/1d7608ac3d4bdaa28c0bdc1805f03fc2.jpg'}, headers={'enctype': 'mutlipart/form-data'}) print(resp.text)
Go
package main import ( "bytes" "fmt" "io/ioutil" "mime/multipart" "net/http" "os" "io" ) func main() { var buff bytes.Buffer writer := multipart.NewWriter(&buff) // 添加form表单参数, 可以添加多个 writer.WriteField("route_str", "xiaofei/1d7608ac3d4bdaa28c0bdc1805f03fc2.jpg") w, _ := writer.CreateFormFile("file_stream", "ywdhzxf.jpg") fd1, _ := os.Open("/Users/xiaofei/Downloads/ywdhzxf.jpg") defer fd1.Close() // 把文件流写入到缓冲区里去 _, _ = io.Copy(w, fd1) writer.Close() //w.Write([]byte("this is a byte")) 如果有字节流直接写入就可以 var client http.Client // 发送请求 resp, err := client.Post("http://127.0.0.1/pic/upload", writer.FormDataContentType(), &buff) if err != nil { fmt.Println(err) return } defer resp.Body.Close() data, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) }