【问题标题】:How can you upload files as a []byte in go?如何在 go 中将文件作为 []byte 上传?
【发布时间】:2017-06-01 02:07:06
【问题描述】:

我想用golang post请求,上传图片,但是我不想传filepath,只想传[]字节 下面的文章不是我需要的,因为它们使用的是 os.Open golang POST data using the Content-Type multipart/form-data

func Upload(url, file string) (err error) {
    // Prepare a form that you will submit to that URL.
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    // Add your image file
    f, err := os.Open(file)
    if err != nil {
        return 
    }
    defer f.Close()
    fw, err := w.CreateFormFile("image", file)
    if err != nil {
        return 
    }
    if _, err = io.Copy(fw, f); err != nil {
        return
    }
    // Add the other fields
    if fw, err = w.CreateFormField("key"); err != nil {
        return
    }
    if _, err = fw.Write([]byte("KEY")); err != nil {
        return
    }
    // Don't forget to close the multipart writer.
    // If you don't close it, your request will be missing the terminating boundary.
    w.Close()

    // Now that you have a form, you can submit it to your handler.
    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return 
    }
    // Don't forget to set the content type, this will contain the boundary.
    req.Header.Set("Content-Type", w.FormDataContentType())

    // Submit the request
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        return 
    }

    // Check the response
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return
}

【问题讨论】:

  • http.request.Body() 是字节流,可能你的问题属于客户端,这些图片是从哪里来的?是网站还是其他客户?
  • 我的请求是这样的,前端和api(api1)是分开的,前端要传递一个base64的参数,在api(api1)中:这个参数会被转换成[]字节,然后通过http post调用另一个api(api2)
  • 这里是我要求的参数 --8D4A8ED669208A7 Content-Disposition:form-data;name="charset" Content-Type:text/plain utf-8 --8D4A8ED669208A7 Content-Disposition:form-data ;名称= “符号” 内容类型:文本/无格式Qlv1mjWGUEq + 7i2FhTGjCa7WwFcZBHlg019JrHgjNJ2D98bEnkHKI9A + SCHM + xaewgaqC2i73lybrRNwzUpKJFlUoVcrnFhuMWbHCI73Zkg + mn8lLJrzMgoqPBTsMxze + 0uDCci7cmpM8ijTMKaxtwWddg910EzDMkQra14TiU4 = --8D4A8ED669208A7内容处置:形状数据;名称= “image_content”;文件名= “123.jpg” 内容-类型:图像/JPEG
  • 我希望这样:if _, err = io.Copy(fw, []byte);错误!=零{返回}
  • 答案已经在示例代码中,即不用io.Copy(fw, f),直接用fw.Write(your-data)写。

标签: http go upload


【解决方案1】:

自从你使用

if _, err = io.Copy(fw, f); err != nil {
    return
}

您也可以将代码编辑为:

  1. 添加新导入:"bytes"
  2. 将方法签名更改为func Upload(url string, file []byte) (err error)
  3. 使用io.Copy(fw, bytes.NewReader(f))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2012-06-26
    • 2016-10-10
    • 2014-11-22
    • 2013-01-27
    • 2013-02-01
    相关资源
    最近更新 更多