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
}

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...