企业微信API上传临时素材
2019-07-31 本文已影响0人
杜子龙
官方API文档在此,不过构造请求很坑,其中HttpDo方法的具体实现在此:
func MaterialUploadByData(data []byte, fillType, accessToken, filename string) (res *MaterialResponse) {
res = &MaterialResponse{}
contentType := ""
filenameToLower := strings.ToLower(filename)
if strings.HasSuffix(filenameToLower, ".jpg") {
contentType = "image/jpg"
} else if strings.HasSuffix(filenameToLower, ".png") {
contentType = "image/png"
} else if strings.HasSuffix(filenameToLower, ".bmp") {
contentType = "image/bmp"
} else if strings.HasSuffix(filenameToLower, ".amr") {
contentType = "voice/amr"
} else if strings.HasSuffix(filenameToLower, ".mp4") {
contentType = "video/mp4"
} else {
contentType = "application/octet-stream"
}
QYURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", accessToken, fillType)
BOUNDARY := strconv.FormatInt(time.Now().Unix(), 10)
bodyBuf := bytes.NewBuffer(nil)
bodyBuf.WriteString(fmt.Sprintf("--%s\r\nContent-Disposition: form-data; name=\"media\";filelength=%s; filename=\"%s\"\r\n"+
"Content-Type: %s\r\n\r\n",
BOUNDARY, strconv.Itoa(len(data)), filename, contentType))
bodyBuf.Write(data)
bodyBuf.WriteString(fmt.Sprintf("\r\n--%s--\r\n", BOUNDARY))
req, err := http.NewRequest("POST", QYURL, bodyBuf)
if err != nil {
log.Errorf("err = %s", err.Error())
res.Errcode = -1
res.Errmsg = err.Error()
return res
}
req.Header.Add("Content-Type", `multipart/form-data; boundary=`+BOUNDARY)
//req.Header.Add("Content-Length", strconv.Itoa(bodyBuf.Len())) //可以省略
resStr, err := httputils.HttpDo(req)
if err != nil {
log.Errorf("err = %s", err.Error())
res.Errcode = -1
res.Errmsg = err.Error()
return
}
err = json.Unmarshal(resStr, res)
if err != nil {
log.Errorf("获取mediaId出错,err = %s", err.Error())
res.Errcode = -1
res.Errmsg = err.Error()
return
}
return
}
type MaterialResponse struct {
Errcode int32 `json:"errcode"`
Errmsg string `json:"errmsg"`
MediaId string `json:"media_id"`
FillType string `json:"type"` //分别有图片(image)、语音(voice)、视频(video),普通文件(file)
CreatedAt string `json:"created_at"`
Url string `json:"url"`
}