欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

go上传图片微信服务器<<临时素材

程序员文章站 2023-11-21 22:43:16
type WxImage struct { Type string `json:"type"` MediaId string `json:"media_id"` CreatedAt int `json:"created_at"` } func UpImage(token, filename stri... ......
type wximage struct {
    type      string  `json:"type"`
    mediaid   string  `json:"media_id"`
    createdat int     `json:"created_at"`
}
func upimage(token, filename string) string {
    //打开文件
    fh, err := os.open(filename)
    if err != nil {
        logs.info("error opening file")
        return ""
    }
    defer fh.close()
    bodybuf := &bytes.buffer{}
    bodywriter := multipart.newwriter(bodybuf)

    filewriter, err := bodywriter.createformfile("image", filepath.base(filename))
    if err != nil {
        logs.info("error writing to buffer")
        return ""
    }

    _, err = io.copy(filewriter, fh)
    if err != nil {
        return ""
    }
    bodywriter.close()
        
    //upload
    req, err := http.newrequest("post", fmt.sprintf("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=image", token), bodybuf)
    req.header.add("content-type", bodywriter.formdatacontenttype())
    urlquery := req.url.query()
    if err != nil {
        return ""
    }
    urlquery.add("access_token", token)
    urlquery.add("type", "image")

    req.url.rawquery = urlquery.encode()
    client := http.client{}
    res, err := client.do(req)
    if err != nil {
        return ""
    }
    defer res.body.close()
    jsonbody, err := ioutil.readall(res.body)

    if err != nil {
        logs.error("上传图片结果失败, err: %v", err)
        return ""
    }
    var result wximage
    json.unmarshal(jsonbody, &result)
    return result.mediaid
}