Open gonetpass opened 3 months ago
func (fs *Files) Encode() (*bytes.Buffer, string, error) { var uploadWriter io.Writer var uploadFile *os.File var err error body := &bytes.Buffer{} writer := multipart.NewWriter(body) defer writer.Close()//应该在遍历结束之后才close for index, name := range fs.indexKey { itemList := fs.files[index][name] for _, item := range itemList { if item["type"] == "field" { fmt.Println(name, item["value"]) writer.WriteField(name, item["value"]) } else { contentType := item["contentType"] if contentType == "" { contentType = "application/octet-stream" } h := fs.createFormFileHeader(name, item["value"], contentType) uploadWriter, err = writer.CreatePart(h) if err != nil { return nil, "", err } uploadFile, err = os.Open(item["path"]) if err != nil { return nil, "", err } _, err = io.Copy(uploadWriter, uploadFile) if err != nil { return nil, "", err } err = uploadFile.Close() if err != nil { return nil, "", err } //源代码在此关闭了write 会导致在处理file的时候提前close掉write } } } return body, writer.FormDataContentType(), nil }