微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

file-upload – 使用Content-Type multipart/form-data的golang POST数据

我试图使用go将图像从我的计算机上传到网站。通常情况下,我使用一个bash脚本向文件传送一个键给serveur:
curl -F "image"=@"IMAGEFILE" -F "key"="KEY" URL

它的工作很好,但我想把这个请求转换成我的golang程序。

http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/

我试过这个链接和许多其他。但对于我尝试的每个代码,服务器的响应是“没有图像发送”。我不知道为什么。如果有人知道上面的例子发生了什么。

谢谢

这里有一些示例代码

总之,你需要使用mime/multipart package来构建表单。

package sample

import (
    "bytes"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

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
}

原文地址:https://www.jb51.cc/go/187617.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐