dousui6488 2018-11-22 16:44 采纳率: 100%
浏览 161
已采纳

如何在同一请求中发布文件和表单字段?

I have the following code which I have tried to use to send a post request where I want to upload a js.map file to bugsnag.

...  
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(filetype, filename)

if err != nil {
    log.Fatal(err)
}

fmt.Printf("Sending %s to bugsnag", filename)

io.Copy(part, file)
writer.Close()
request, err := http.NewRequest("POST", bugsnagUrl, body)

if err != nil {
    log.Fatal(err)
}

request.Header.Add("Content-Type", writer.FormDataContentType())

// This is where my problem seems to be, I can't add form values this way because the map is nil
request.Form.Add("apiKey", bugsnagToken)
request.Form.Add("minifiedUrl", fileurl)
request.Form.Add("sourceMap", filename)
request.Form.Add("overwrite", "true")
client := &http.Client{}

response, err := client.Do(request)

if err != nil {
    log.Fatal(err)
}
defer response.Body.Close()

The above example gives the following error

panic: assignment to entry in nil map

goroutine 1 [running]: net/url.url.Values.Add(...)

I have been unable to find any examples on how to do this, I used the example on how to upload a file from this question to get this far.

I seem to be able to post the file but how can I post a file and also include post form values with my request?

  • 写回答

1条回答 默认 最新

  • dongyou2279 2018-11-22 17:03
    关注

    You should add form fields like this

    writer.WriteField("apiKey", bugsnagToken)
    writer.WriteField("minifiedUrl", fileurl)
    writer.WriteField("sourceMap", filename)
    writer.WriteField("overwrite", "true")
    writer.Close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题