Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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
}

大佬总结

以上是大佬教程为你收集整理的file-upload – 使用Content-Type multipart/form-data的golang POST数据全部内容,希望文章能够帮你解决file-upload – 使用Content-Type multipart/form-data的golang POST数据所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。