加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:42:08 所属栏目:大数据 来源:网络整理
导读:我试图使用go将图像从我的计算机上传到网站。通常情况下,我使用一个bash脚本向文件传送一个键给serveur: curl -F "image"=@"IMAGEFILE" -F "key"="KEY" URL 它的工作很好,但我想把这个请求转换成我的golang程序。 http://matt.aimonetti.net/posts/2013/0
我试图使用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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读