wangluozhe / requests

用于快速请求HTTP或HTTPS,并支持修改ja3、ja4指纹
GNU General Public License v3.0
430 stars 100 forks source link

multipart有bug ,Files结构体转FormFile #73

Open gonetpass opened 3 months ago

gonetpass commented 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
}