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 }
上一篇: python-day8(正式学习)
下一篇: 创建模式--工厂模式、抽象工厂模式