http - 如何在 go 中将文件作为 []byte 上传?

标签 http go upload

我想用golang post请求,上传图片,但是不想传filepath,只想传[] byte 下面的文章不是我需要的,因为都用到了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
}

最佳答案

自从你使用

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))

关于http - 如何在 go 中将文件作为 []byte 上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297376/

相关文章:

http - 如何根据 HTTP 请求获取响应 header ?

angularjs - 避免在 AngularJS 中使用 $resource 发送选项(预检)的最佳方法是什么

java - 如何创建所有 Android 设备通用的相机 Action

android - 缓慢上传到正在运行的 Android 模拟器

rest - 如何在不实际执行的情况下模拟 HTTP DELETE 操作的后果

ios - 将 curl 命令转换为 AFNetworking 调用

golang程序导入 "github.com/ethereum/go-ethereum/accounts/keystore"构建错误

go - 当范围超过 JSON 数组时无法迭代所有索引

xml - GoLang XML编码(marshal)处理自定义(无根元素的编码(marshal))

php - 即使 PHP 在 IE 中也有 'bugs'