|
- package youlianghui
-
- import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "mime/multipart"
- "net/http"
- "os"
- )
-
- // MultipartFormDataRequest 封装 multipart/form-data 请求
- func MultipartFormDataRequest(url string, fields map[string]string, files map[string]string, headers map[string]string) ([]byte, error) {
- // 创建一个缓冲区来存储表单数据
- var b bytes.Buffer
- w := multipart.NewWriter(&b)
-
- // 添加文本字段
- for key, value := range fields {
- if err := addFormValue(w, key, value); err != nil {
- return nil, err
- }
- }
-
- // 添加文件字段
- for fieldName, filePath := range files {
- file, err := os.Open(filePath)
- if err != nil {
- return nil, fmt.Errorf("error opening file %s: %v", filePath, err)
- }
- defer file.Close()
-
- part, err := w.CreateFormFile(fieldName, filePath)
- if err != nil {
- return nil, fmt.Errorf("error creating form file %s: %v", fieldName, err)
- }
-
- if _, err := io.Copy(part, file); err != nil {
- return nil, fmt.Errorf("error copying file %s to part: %v", filePath, err)
- }
- }
-
- // 完成多部分表单
- if err := w.Close(); err != nil {
- return nil, fmt.Errorf("error closing multipart writer: %v", err)
- }
-
- // 创建请求
- req, err := http.NewRequest("POST", url, &b)
- if err != nil {
- return nil, fmt.Errorf("error creating request: %v", err)
- }
-
- // 设置头部
- req.Header.Set("Content-Type", w.FormDataContentType())
- for key, value := range headers {
- req.Header.Set(key, value)
- }
-
- // 发送请求
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("error sending request: %v", err)
- }
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body) // 读取响应
- if err != nil {
- return nil, err
- }
-
- return body, nil
- }
-
- // addFormValue 辅助函数:添加表单值
- func addFormValue(w *multipart.Writer, key, value string) error {
- fw, err := w.CreateFormField(key)
- if err != nil {
- return fmt.Errorf("error creating form field %s: %v", key, err)
- }
- _, err = fw.Write([]byte(value))
- return err
- }
|