广告平台(站长使用)
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 

85 satır
2.0 KiB

  1. package youlianghui
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "mime/multipart"
  8. "net/http"
  9. "os"
  10. )
  11. // MultipartFormDataRequest 封装 multipart/form-data 请求
  12. func MultipartFormDataRequest(url string, fields map[string]string, files map[string]string, headers map[string]string) ([]byte, error) {
  13. // 创建一个缓冲区来存储表单数据
  14. var b bytes.Buffer
  15. w := multipart.NewWriter(&b)
  16. // 添加文本字段
  17. for key, value := range fields {
  18. if err := addFormValue(w, key, value); err != nil {
  19. return nil, err
  20. }
  21. }
  22. // 添加文件字段
  23. for fieldName, filePath := range files {
  24. file, err := os.Open(filePath)
  25. if err != nil {
  26. return nil, fmt.Errorf("error opening file %s: %v", filePath, err)
  27. }
  28. defer file.Close()
  29. part, err := w.CreateFormFile(fieldName, filePath)
  30. if err != nil {
  31. return nil, fmt.Errorf("error creating form file %s: %v", fieldName, err)
  32. }
  33. if _, err := io.Copy(part, file); err != nil {
  34. return nil, fmt.Errorf("error copying file %s to part: %v", filePath, err)
  35. }
  36. }
  37. // 完成多部分表单
  38. if err := w.Close(); err != nil {
  39. return nil, fmt.Errorf("error closing multipart writer: %v", err)
  40. }
  41. // 创建请求
  42. req, err := http.NewRequest("POST", url, &b)
  43. if err != nil {
  44. return nil, fmt.Errorf("error creating request: %v", err)
  45. }
  46. // 设置头部
  47. req.Header.Set("Content-Type", w.FormDataContentType())
  48. for key, value := range headers {
  49. req.Header.Set(key, value)
  50. }
  51. // 发送请求
  52. client := &http.Client{}
  53. resp, err := client.Do(req)
  54. if err != nil {
  55. return nil, fmt.Errorf("error sending request: %v", err)
  56. }
  57. defer resp.Body.Close()
  58. body, err := ioutil.ReadAll(resp.Body) // 读取响应
  59. if err != nil {
  60. return nil, err
  61. }
  62. return body, nil
  63. }
  64. // addFormValue 辅助函数:添加表单值
  65. func addFormValue(w *multipart.Writer, key, value string) error {
  66. fw, err := w.CreateFormField(key)
  67. if err != nil {
  68. return fmt.Errorf("error creating form field %s: %v", key, err)
  69. }
  70. _, err = fw.Write([]byte(value))
  71. return err
  72. }