How can you upload files as a []byte in go?

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

How can you upload files as a []byte in go?

问题

我想使用golang进行POST请求并上传图片,但我不想传递文件路径,只想传递[]byte类型的数据。

以下是我找到的一篇文章,但不符合我的需求,因为它使用了os.Open函数:
https://stackoverflow.com/questions/20205796/golang-post-data-using-the-content-type-multipart-form-data

func Upload(url, file string) (err error) {
    // 准备一个表单,将要提交到指定的URL。
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    // 添加图片文件
    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
    }
    // 添加其他字段
    if fw, err = w.CreateFormField("key"); err != nil {
        return
    }
    if _, err = fw.Write([]byte("KEY")); err != nil {
        return
    }
    // 不要忘记关闭multipart writer。
    // 如果不关闭,请求将缺少终止边界。
    w.Close()

    // 现在你有了一个表单,可以将其提交给处理程序。
    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return
    }
    // 不要忘记设置Content-Type,它将包含边界信息。
    req.Header.Set("Content-Type", w.FormDataContentType())

    // 提交请求
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        return
    }

    // 检查响应
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return
}

希望这可以帮到你!

英文:

I would like to use golang post request, upload pictures, but I do not want to pass filepath, just want to pass [] byte
The following article are not what I need because they are used os.Open
https://stackoverflow.com/questions/20205796/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
}

答案1

得分: 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))
英文:

Since you use

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

You may as well edit your code to:

  1. Add new import: "bytes"
  2. Change the method signature to func Upload(url string, file []byte) (err error)
  3. Use io.Copy(fw, bytes.NewReader(f))

huangapple
  • 本文由 发表于 2017年6月1日 10:07:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/44297376.html
匿名

发表评论

匿名网友

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

确定