qazxsw1 发表于 2015-12-24 10:05:59

golang 上传文件到php

func upimgAction(imgurl string, url string) {  
  path := imgurl
  extraParams := mapstring{
  "param1":    "1",
  "param2": "2",
  "param3":   "3",
  }
  request, err := newfileUploadRequest(url, extraParams, "Filedata", path)//Filedata文件名称
  if err != nil {
  log.Error(err)
  }
  //fmt.Println(request)
  
  resp, err := Gclient.Do(request)
  if err != nil {
  log.Error(err)
  } else {
  body := &bytes.Buffer{}
  _, err := body.ReadFrom(resp.Body)
  if err != nil {
  log.Error(err)
  }
  resp.Body.Close()
  //fmt.Println(resp.StatusCode)
  //fmt.Println(resp.Header)
  fmt.Println(body)
  }
  }
  func newfileUploadRequest(uri string, params mapstring, paramName, path string) (*http.Request, error) {
  file, err := os.Open(path)
  if err != nil {
  return nil, err
  }
  defer file.Close()
  
  body := &bytes.Buffer{}
  writer := multipart.NewWriter(body)
  for key, val := range params {
  _ = writer.WriteField(key, val)
  }
  formcontenttype := writer.FormDataContentType()
  part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  if err != nil {
  return nil, err
  }
  _, err = io.Copy(part, file)
  
  err = writer.Close()
  if err != nil {
  return nil, err
  }
  //fmt.Println(body)
  request, err := http.NewRequest("POST", uri, body)
  request.Header.Set("Content-Type", formcontenttype)
  return request, err
  }
页: [1]
查看完整版本: golang 上传文件到php