为了模拟客户端和服务器端,我这儿开了两个进程,进程A(监听地址:http://192.168.50.250:8080 路由/objects)进程B(监听地址:http://192.168.50.250:8081 路由:/objetcs)方法都是post。进程A是监听客户上传的文件,然后模拟http clien上传给进程B。在B中将文件存储或者将内容打印。
进程A post /ojects:
func PostFile(c *gin.Context){
var b bytes.Buffer
w := multipart.NewWriter(&b)
c.Request.ParseMultipartForm(100000)
multiPartform ,_:= c.MultipartForm()
err := utils.CreatFormFiles(&b,multiPartform,w)
if err != nil{
fmt.Println(err)
return
}
request,err:=http.NewRequest(http.MethodPost,"http://192.168.50.250:8081/objects",&b)
if err != nil{
fmt.Println(err)
return
}
//模拟客户端请求,还可以在request.Form中添加其他信息,如username,password等key_values
client := http.Client{Timeout:5*time.Second}
request.Header.Set("Content-Type",w.FormDataContentType())
resp,err := client.Do(request)
if err != nil{
fmt.Println(err)
return
}
handlers.SendRespense(c,resp.StatusCode,"ok")
}
CreatFormFiles:
func CreatFormFiles(b *bytes.Buffer,form *multipart.Form,w *multipart.Writer)error{
for name,files := range form.File{
for _,file := range files{
f,err := file.Open()
if err != nil{
return err
}
fw,err := w.CreateFormFile(name,file.Filename)
if err != nil{
return err
}
_,err = io.Copy(fw,f)
if err != nil{
return err
}
}
}
w.Close() //要关闭,会将w.w.boundary刷写到w.writer中
return nil
}
进程B post /obcjetcs:
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Content-Type", "multipart/form-data")
c.Request.ParseMultipartForm(5000000)
form,err := c.MultipartForm()
if err != nil{
c.JSON(500,"bad form")
}
fheaders := form.File["upload"]
for _,fheader := range fheaders{
fmt.Printf("name:%s,f:%v","upload",fheader.Filename)
}
c.JSON(200,"ok")
这样我们就可以在前端上传多个文件。我这里示范的是在upload这个key里带了三个文件。有疑问加站长微信联系(非本文作者)