How can I upload a file to server, without browser, using go?

huangapple go评论80阅读模式
英文:

How can I upload a file to server, without browser, using go?

问题

trsp := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
Url := "https://127.0.0.1:8080"
client := &http.Client{Transport: trsp}
request, _ := http.NewRequest("POST", Url, nil)
k, _ := os.Open(nameOfFile)
request.Header.Set("Action", "download"+k.Name())
...
...
client.Do(request)

我有一个服务器,我需要将文件上传到服务器。我应该如何处理请求?我认为我应该将文件写入request.Body,然后在服务器端处理这个请求。

英文:
trsp := &http.Transport{
	TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
Url := "https://127.0.0.1:8080"
client := &http.Client{Transport: trsp}
request, _ := http.NewRequest("POST", Url, nil)
k, _ := os.Open(nameOfFile)
request.Header.Set("Action", "download"+k.Name())
...
...
client.Do(request)

I have server, and I need to upload to server a file. What should I do with request? As I think I shoud write into request.Body and then, from server handle this query

答案1

得分: 2

你需要使用"mime/multipart"包来创建HTTP请求的请求体,就像这样。

http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/

func newfileUploadRequest(uri string, params map[string]string, 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)
  part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  if err != nil {
      return nil, err
  }
  _, err = io.Copy(part, file)

  for key, val := range params {
      _ = writer.WriteField(key, val)
  }
  err = writer.Close()
  if err != nil {
      return nil, err
  }

  return http.NewRequest("POST", uri, body)
}
英文:

you need use the "mime/multipart"package to make the http body. like this.

http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/

func newfileUploadRequest(uri string, params map[string]string, 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)
  part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  if err != nil {
      return nil, err
  }
  _, err = io.Copy(part, file)

  for key, val := range params {
      _ = writer.WriteField(key, val)
  }
  err = writer.Close()
  if err != nil {
      return nil, err
  }

  return http.NewRequest("POST", uri, body)
}

huangapple
  • 本文由 发表于 2015年8月21日 16:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/32136093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定