golang POST数据使用Content-Type multipart / form-data [英] golang POST data using the Content-Type multipart/form-data

查看:15631
本文介绍了golang POST数据使用Content-Type multipart / form-data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用go将图片从我的电脑上传到网站。通常,我使用一个bash脚本向attur发送文件一个键:

I'm trying to upload images from my computer to a website using go. Usually, I use a bash script who send file a key to the serveur:

curl -F "image"=@"IMAGEFILE" -F "key"="KEY" URL

将此请求转换为我的golang程序。

it's work fine, but I'm trying to convert this request into my golang program.

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

我试过这个链接和许多其他。但对于我尝试的每个代码,服务器的响应是没有图像发送。我不知道为什么。

I tried this link and many other. But for each code that I try, the response for the server is "no image sended". And I've no idea why. If someone know what's happend with the exemple above.

感谢

推荐答案

以下是一些示例代码。

简而言之,您需要使用 mime / multipart 构建表单。

In short, you'll need to use the mime/multipart package to build the form.

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
}

这篇关于golang POST数据使用Content-Type multipart / form-data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆