New temporary material development of the micro-channel public number (eight)

First, the new temporary material

No public often need to use some temporary scenes multimedia material, for example in the use of the interface in particular, to send a message, the operation of multimedia files, access and call multimedia messages, etc., are carried out by the media_id. Material management interface is open to all certified subscription number and service number. Through this interface, a number of the public can add temporary material (ie temporary upload multimedia files).

important point:

1, media_id temporary material is reusable.

2, the media file is saved in the micro-channel background time of 3 days, 3 days, i.e. media_id failure.

3, upload temporary clip format, the size limit is consistent with the public platform's official website.

Pictures (image): 2M, support the PNG \ JPEG \ JPG \ GIF format

Voice (voice): 2M, players no longer than 60s, supports AMR \ MP3 format

Video (video): 10MB, support MP4 format

Thumbnail (thumb): 64KB, JPG format support

4, use https call this interface.

Interface call requesting explanation

http request method: POST / FORM, use https https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE call sample (using curl command, a multimedia file upload form FORM way ): curl -F [email protected] "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Parameter Description

parameter Do you have to Explanation
access_token Yes Call Interface credentials
type Yes Media file types, respectively picture (image), voice (voice), video (video) and thumbnail (thumb)
media Yes form-data in the media file identification, there filename, filelength, content-type information

Returning to the description

Where the correct return JSON packet under the following results:

{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
parameter description
type Media file types, respectively picture (image), voice (voice), video (video) and thumbnail (thumb, mainly for the thumbnail video and music formats)
media_id After uploading your media files, obtain identification
created_at Media file upload timestamp

Return packet error conditions the following example JSON (Example invalid media type error) at:

{"errcode":40004,"errmsg":"invalid media type"}

According to the above interface, we define a method to upload a temporary material, including the file directory and file type of these two parameters, we here still using RestTemplate tools for file upload

 

/**
     * 上传临时素菜
     * 1、临时素材media_id是可复用的。
     * 2、媒体文件在微信后台保存时间为3天,即3天后media_id失效。
     * 3、上传临时素材的格式、大小限制与公众平台官网一致。
     * @param filePath
     * @param type
     * @return
     */
    public String uploadFile(String filePath,String type) {

        String accessToken = accessTokenUtil.getAccessToken();
        if (accessToken != null) {
            String url = URIConstant.MEDIA_UPLOAD_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("TYPE", type);
            log.info("MEDIA_UPLOAD_URL:{}",url);

            //设置请求体,注意是LinkedMultiValueMap
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            form.add("media", fileSystemResource);

            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            //用HttpEntity封装整个请求报文
            HttpEntity<MultiValueMap<String, Object>> data = new HttpEntity<>(form, headers);
            try{
                //这里RestTemplate请求返回的字符串直接转换成JSONObject会报异常,后续深入找一下原因
                String resultString = restTemplate.postForObject(url, data, String.class);
                log.info("上传返回的信息是:{}",resultString);
                if(!StringUtils.isEmpty(resultString)){
                    JSONObject jsonObject = JSONObject.parseObject(resultString);
                    return jsonObject.getString("media_id");
                }
            }catch (Exception e){
                log.error(e.getMessage());
            }

        }
        return null;
    }

We create a new Controller to submit our upload request swagger in and test our code is correct

@ApiOperation(value = "上传临时素材")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="filePath",value="文件位置", paramType="query",dataType="String"),
            @ApiImplicitParam(name="type",value="媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)", paramType="query",dataType="String"),

    })
    public Object upload(String filePath, String type) throws Exception{

        String result = uploadUtil.uploadFile(filePath,type);
        return result;
    }

Our project started, enter a valid file path (if here is the picture type) in the swagger in, type set image

 

You can see, we have successfully uploaded the temporary files, and get to the media_id the file (this follow-up is very important !!!)

 

Second, obtain a temporary material

Temporary material is mainly divided into three categories (picture, audio, video), pictures and audio files downloaded to the local support, support for video file to obtain the URL of the video

(1) obtain a temporary Pictures

 

/**
     * 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)
     * 1、如果是图片,则下载图片
     */
    public ResponseEntity<byte[]> getImage(String mediaId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null) {
            String url = URIConstant.MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("MEDIA_ID", mediaId);
            log.info("MEDIA_GET_URL:{}", url);

            String fileName = mediaId+ ".jpg";
            HttpHeaders headers = new HttpHeaders();
            try {
                fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentDispositionFormData("attachment", fileName);// 文件名称
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
            return responseEntity;
        }
        return null;
    }

(2) obtain a temporary audio

/**
     * 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)
     * 1、如果是声音,则下载声音
     */
    public ResponseEntity<byte[]> getVoice(String mediaId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null) {
            String url = URIConstant.MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("MEDIA_ID", mediaId);
            log.info("MEDIA_GET_URL:{}", url);

            String fileName = mediaId+ ".speex";
            HttpHeaders headers = new HttpHeaders();
            try {
                fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentDispositionFormData("attachment", fileName);// 文件名称
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
            return responseEntity;
        }
        return null;
    }

 (3) to obtain video footage address

/**
     * 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)
     * 2、如果是视频,则返回视频的地址
     */
    public String getVedio(String mediaId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null) {
            String url = URIConstant.MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("MEDIA_ID", mediaId);
            log.info("MEDIA_GET_URL:{}", url);

            String responseString = restTemplate.getForObject(url,String.class);
            return responseString;
        }
        return null;
    }

 Third, the test

Here we only temporary upload and download picture material temporary picture material, for example, we get a new type of material according to media_id temporary picture in our Controller Methods

We have just uploaded our successful return of temporary material media_id passed our approach

 

We can see our swagger returned with Download file hyperlinks, click here to download our pictures, of course, we can enter directly in the browser directly address our full request

http://localhost/material/getFile?mediaId=C3Vd7uR-MKY5bOkyT5hWGaS-icl3av7GahjM9E9Hx9i8nonxg4PNtE-s7TbYSseV

Click the Download File, we have successfully downloaded to the temporary upload pictures

Try to open the file, we can see that this is really our upload pictures

 Here posted the complete code, self-modified to obtain other types of temporary files, not repeat them

UploadUtil.java
package com.xu.wemall.components.weixin;

import com.alibaba.fastjson.JSONObject;
import com.xu.wemall.commons.constants.URIConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;

/**
 * 功能:临时素材工具类
 */
@Slf4j
@Component
public class UploadUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    /**
     * 上传临时素菜
     * 1、临时素材media_id是可复用的。
     * 2、媒体文件在微信后台保存时间为3天,即3天后media_id失效。
     * 3、上传临时素材的格式、大小限制与公众平台官网一致。
     * @param filePath
     * @param type
     * @return
     */
    public String uploadFile(String filePath,String type) {

        String accessToken = accessTokenUtil.getAccessToken();
        if (accessToken != null) {
            String url = URIConstant.MEDIA_UPLOAD_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("TYPE", type);
            log.info("MEDIA_UPLOAD_URL:{}",url);

            //设置请求体,注意是LinkedMultiValueMap
            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            form.add("media", fileSystemResource);

            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            //用HttpEntity封装整个请求报文
            HttpEntity<MultiValueMap<String, Object>> data = new HttpEntity<>(form, headers);
            try{
                //这里RestTemplate请求返回的字符串直接转换成JSONObject会报异常,后续深入找一下原因
                String resultString = restTemplate.postForObject(url, data, String.class);
                log.info("上传返回的信息是:{}",resultString);
                if(!StringUtils.isEmpty(resultString)){
                    JSONObject jsonObject = JSONObject.parseObject(resultString);
                    return jsonObject.getString("media_id");
                }
            }catch (Exception e){
                log.error(e.getMessage());
            }

        }
        return null;
    }

    /**
     * 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)
     * 1、如果是图片,则下载图片
     */
    public ResponseEntity<byte[]> getImage(String mediaId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null) {
            String url = URIConstant.MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("MEDIA_ID", mediaId);
            log.info("MEDIA_GET_URL:{}", url);

            String fileName = mediaId+ ".jpg";
            HttpHeaders headers = new HttpHeaders();
            try {
                fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentDispositionFormData("attachment", fileName);// 文件名称
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
            return responseEntity;
        }
        return null;
    }

    /**
     * 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)
     * 1、如果是声音,则下载声音
     */
    public ResponseEntity<byte[]> getVoice(String mediaId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null) {
            String url = URIConstant.MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("MEDIA_ID", mediaId);
            log.info("MEDIA_GET_URL:{}", url);

            String fileName = mediaId+ ".speex";
            HttpHeaders headers = new HttpHeaders();
            try {
                fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentDispositionFormData("attachment", fileName);// 文件名称
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
            return responseEntity;
        }
        return null;
    }

    /**
     * 公众号可以使用本接口获取临时素材(即下载临时的多媒体文件)
     * 2、如果是视频,则返回视频的地址
     */
    public String getVedio(String mediaId){

        String accessToken = accessTokenUtil.getAccessToken();
        if(accessToken != null) {
            String url = URIConstant.MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken)
                    .replace("MEDIA_ID", mediaId);
            log.info("MEDIA_GET_URL:{}", url);

            String responseString = restTemplate.getForObject(url,String.class);
            return responseString;
        }
        return null;
    }



}


Thank you, next time we continue to say!

Guess you like

Origin www.cnblogs.com/xulijun137/p/12213629.html