TOP

go上传图片微信服务器<<临时素材
2019-08-14 00:07:26 】 浏览:93
Tags:上传 图片 服务器 < 临时 素材

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
}

 


go上传图片微信服务器<<临时素材 https://www.cppentry.com/bencandy.php?fid=78&id=228491

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇2.GO-可变参数函数、匿名函数和函.. 下一篇golang使用json格式实现增删查改