Post请求上传文件

文件上传
创建于:2021年02月28日

import (
    "bytes"
    "encoding/json"
    "io"
    "io/ioutil"
    "mime/multipart"
    "net/http"
)


// 上传文件
// url                请求地址
// params        post form里数据
// nameField  请求地址上传文件对应field
// fileName     文件名
// file               文件
func UploadFile(url string, params map[string]string, nameField, fileName string, file io.Reader) ([]byte, error) {
    body := new(bytes.Buffer)

    writer := multipart.NewWriter(body)

    formFile, err := writer.CreateFormFile(nameField, fileName)
    if err != nil {
        return nil, err
    }

    _, err = io.Copy(formFile, file)
    if err != nil {
        return nil, err
    }

    for key, val := range params {
        _ = writer.WriteField(key, val)
    }

    err = writer.Close()
    if err != nil {
        return nil, err
    }

    req, err := http.NewRequest("POST", url, body)
    if err != nil {
        return nil, err
    }
    req.Header.Add("Content-Type", writer.FormDataContentType())

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    return content, nil
}