golang post 上传文件

golang post 上传文件

地址:https://github.com/FakerGit/go-tools/tree/master/http

//注意client 本身是连接池,不要每次请求时创建client
var (
    HttpClient = &http.Client{
        Timeout: 3 * time.Second,
    }
)

// 上传文件
// 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.Set("Content-Type","multipart/form-data")
    req.Header.Add("Content-Type", writer.FormDataContentType())

    resp, err := HttpClient.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
}

你可能感兴趣的:(golang post 上传文件)