zoukankan      html  css  js  c++  java
  • go上传图片微信服务器<<临时素材

    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
    }
  • 相关阅读:
    canvas-color的几种设置
    canvas-2lineCap.html
    canvas-2lineJoin.html
    canvas-0trasform.html
    总体、个体和简单随机样本
    大数定律
    切比雪夫不等式
    B1032. 挖掘机技术哪家强
    Array(数组)对象-->join() 方法
    Array(数组)对象-->shift() 方法
  • 原文地址:https://www.cnblogs.com/yewook/p/11304539.html
Copyright © 2011-2022 走看看