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

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

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,然后在服务器端处理这个请求。

英文:
  1. trsp := &http.Transport{
  2. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  3. }
  4. Url := "https://127.0.0.1:8080"
  5. client := &http.Client{Transport: trsp}
  6. request, _ := http.NewRequest("POST", Url, nil)
  7. k, _ := os.Open(nameOfFile)
  8. request.Header.Set("Action", "download"+k.Name())
  9. ...
  10. ...
  11. 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/

  1. func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
  2. file, err := os.Open(path)
  3. if err != nil {
  4. return nil, err
  5. }
  6. defer file.Close()
  7. body := &bytes.Buffer{}
  8. writer := multipart.NewWriter(body)
  9. part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  10. if err != nil {
  11. return nil, err
  12. }
  13. _, err = io.Copy(part, file)
  14. for key, val := range params {
  15. _ = writer.WriteField(key, val)
  16. }
  17. err = writer.Close()
  18. if err != nil {
  19. return nil, err
  20. }
  21. return http.NewRequest("POST", uri, body)
  22. }
英文:

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/

  1. func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
  2. file, err := os.Open(path)
  3. if err != nil {
  4. return nil, err
  5. }
  6. defer file.Close()
  7. body := &bytes.Buffer{}
  8. writer := multipart.NewWriter(body)
  9. part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  10. if err != nil {
  11. return nil, err
  12. }
  13. _, err = io.Copy(part, file)
  14. for key, val := range params {
  15. _ = writer.WriteField(key, val)
  16. }
  17. err = writer.Close()
  18. if err != nil {
  19. return nil, err
  20. }
  21. return http.NewRequest("POST", uri, body)
  22. }

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:

确定