执行HTTP POST请求上传文件

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

Go http POST file

问题

我真的很新手Go语言,我需要在Go微服务中集成Zamzar。我需要POST一个文件和一个数据类型(字符串)。

使用curl的示例代码如下:

 -u user:pass \
 -X POST \
 -F "source_file=@/tmp/portrait.gif" \
 -F "target_format=png"

这是我目前的代码:

client := &http.Client{}

req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", nil)

req.SetBasicAuth("user", "pass")

resp, err := client.Do(req)

if err != nil {
  fmt.Printf("Error : %s", err)
} else {
  fmt.Println(resp)
}

我如何将target_format作为字符串发送,将source_file作为文件发送?我已经有了文件([]byte

英文:

I'm really new in Go and I have to integrate Zamzar in a Go microservice. I need to POST a file and a data type (string).

Doing a curl looks like this:

 -u user:pass \
 -X POST \
 -F "source_file=@/tmp/portrait.gif" \
 -F "target_format=png"

This is what I have so far:

client := &http.Client{}

req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", nil)

req.SetBasicAuth("user", "pass")

resp, err := client.Do(req)

if err != nil {
  fmt.Printf("Error : %s", err)
} else {
  fmt.Println(resp)
}

How can I send the target_format as a string and source_file as a file? I already have the file ([]byte)
1: https://developers.zamzar.com/docs

答案1

得分: 2

使用multipart.Writer来创建请求体:

var buf bytes.Buffer
mpw := multipart.NewWriter(&buf)
w, err := mpw.CreateFormFile("source_file", "portrait.gif")
if err != nil {
   // 处理错误
}
if _, err := w.Write(imageBytes); err != nil {
   // 处理错误
}
if err := mpw.WriteField("target_format", "png"); err != nil {
  // 处理错误
}
if err := mpw.Close(); err != nil {
   // 处理错误
}

req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", &buf)
req.Header.Set("Content-Type", mpw.FormDataContentType())

... 继续之前的操作
英文:

Use multipart.Writer to create the request body:

 var buf bytes.Buffer
 mpw := multipart.NewWriter(&buf)
 w, err := mpw.CreateFormFile("source_file", "portrait.gif")
 if err != nil {
    // handle error
 }
 if _, err := w.Write(imageBytes); err != nil {
    // handle error
 }
 if err := mpw.WriteField("target_format", "png"); err != nil {
   // handle error
 }
 if err := mpw.Close(); err != nil {
    // handle error
 }

 req, err := http.NewRequest("GET", "https://sandbox.zamzar.com/v1/jobs", &buf)
 req.Header.Set("Content-Type", mpw.FormDataContentType())
 
 ... continue as before.

huangapple
  • 本文由 发表于 2016年11月16日 04:32:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/40619171.html
匿名

发表评论

匿名网友

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

确定