github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mp/base/uploadimg.go (about)

     1  package base
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/chanxuehong/wechat/mp/core"
     9  )
    10  
    11  // UploadImage 上传图片到微信服务器, 返回的图片url给其他场景使用, 比如图文消息, 卡卷, POI.
    12  func UploadImage(clt *core.Client, imgFilePath string) (url string, err error) {
    13  	file, err := os.Open(imgFilePath)
    14  	if err != nil {
    15  		return
    16  	}
    17  	defer file.Close()
    18  
    19  	return UploadImageFromReader(clt, filepath.Base(imgFilePath), file)
    20  }
    21  
    22  // UploadImageFromReader 上传图片到微信服务器, 返回的图片url给其他场景使用, 比如图文消息, 卡卷, POI.
    23  //
    24  //	NOTE: 参数 filename 不是文件路径, 是 multipart/form-data 里面 filename 的值.
    25  func UploadImageFromReader(clt *core.Client, filename string, reader io.Reader) (url string, err error) {
    26  	const incompleteURL = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="
    27  
    28  	var fields = []core.MultipartFormField{
    29  		{
    30  			IsFile:   true,
    31  			Name:     "media",
    32  			FileName: filename,
    33  			Value:    reader,
    34  		},
    35  	}
    36  	var result struct {
    37  		core.Error
    38  		URL string `json:"url"`
    39  	}
    40  	if err = clt.PostMultipartForm(incompleteURL, fields, &result); err != nil {
    41  		return
    42  	}
    43  	if result.ErrCode != core.ErrCodeOK {
    44  		err = &result.Error
    45  		return
    46  	}
    47  	url = result.URL
    48  	return
    49  }