go 通过http发送图片file内容
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "bufio" "io" "mime/multipart" "net/smtp" )
type addfeature struct { subid int `json:"subid"` file []byte `json:"file"` } func AddTemplateWeb(addr string) { // 创建表单文件 // CreateFormFile 用来创建表单,第一个参数是字段名,第二个参数是文件名 var feat addfeature buf := new(bytes.Buffer) writer := multipart.NewWriter(buf) writer.WriteField("sublib", "1") formFile, err := writer.CreateFormFile("file", "5.jpg") if err != nil { fmt.Println("Create form file failed: %s\n", err) } // 从文件读取数据,写入表单 srcFile, err := os.Open("/home/wei/1.jpg") if err != nil { fmt.Println("%Open source file failed: s\n", err) } defer srcFile.Close() _, err = io.Copy(formFile, srcFile) if err != nil { fmt.Println("Write to form file falied: %s\n", err) } // 发送表单 contentType := writer.FormDataContentType() writer.Close() // 发送之前必须调用Close()以写入结尾行 re, err := http.Post(addr, contentType, buf) fmt.Println(re) return }