作者:tomorrow | 来源:互联网 | 2023-06-06 18:13
我将io与GO multipart一起使用将文件上传到本地服务器,并且此功能每次都失败。 (这只是表单请求的一部分)
func httpreq(uri string,params map[string]interface{},fieldname,filename string,filebuf []byte) (*http.Request,error) {
pr,pw := io.Pipe()
writer := multipart.NewWriter(pw)
go func() {
defer pw.Close()
r := bytes.NewReader(filebuf)
part1,err := writer.CreateFormFile(fieldname,filename)
if err != nil {
return
}
if _,err = io.Copy(part1,r); err != nil {
return
}
// encode params into Json
var j []byte
j,err = json.Marshal(params)
if err != nil {
return
}
part2,err := writer.CreateFormField("json")
if err != nil {
return
}
_,err = io.Copy(part2,bytes.NewBuffer(j))
if err != nil {
return
}
if err = writer.Close(); err != nil {
return
}
}()
req,err := http.NewRequest("POST",uri,pr)
if err != nil {
return nil,err
}
req.Header.Set("Content-Type",writer.FormDataContentType())
fmt.Printf("---> %+v",req)
return req,err
}
我希望请求这样的东西
--f82711203f053f26bd2ea538ab381e30ec1468bff784e34174b11bb679dc
Content-Disposition: form-data; name="file"; filename="nov.txt"
Content-Type: application/octet-stream
November 2019
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
--f82711203f053f26bd2ea538ab381e30ec1468bff784e34174b11bb679dc
Content-Disposition: form-data; name="json"
{"data_profile_id":"1","file_sha":"12345678","no_cache":true,"service_name":"test","tenant_id":"tenant"}
--f82711203f053f26bd2ea538ab381e30ec1468bff784e34174b11bb679dc--
但是我明白了
--c3b154dc079686ba162e0ab057c59580932ebab25294569201ef854394a7
Content-Disposition: form-data; name="file"; filename="102.pdf"
Content-Type: application/octet-stream
--c3b154dc079686ba162e0ab057c59580932ebab25294569201ef854394a7
Content-Disposition: form-data; name="json"
如果我搬出一部分
// encode params into Json
var j []byte
j,bytes.NewBuffer(j))
if err != nil {
return
}
那似乎让我有点接近预期
--f82711203f053f26bd2ea538ab381e30ec1468bff784e34174b11bb679dc
Content-Disposition: form-data; name="file"; filename="nov.txt"
Content-Type: application/octet-stream
November 2019
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
--f82711203f053f26bd2ea538ab381e30ec1468bff784e34174b11bb679dc
这里有专家,我想念什么?