微信小程序在实现客服功能时,有时候需要自动回复一张图片给用户,这时候,我们需要提前将图片上传到微信小程序的素材库。
然后微信客服才能将图片回复给用户。在这儿,我想插句嘴,微信小程序目前只支持临时素材库,不支持永久素材库。
小编在做素材上传时,在这儿被这个坑坑了许久。
import com.alibaba.fastjson.JSONObject;
import com.dftcmedia.tckk.microservice.sskx.microapp.config.ClientProperties;
import com.dftcmedia.tckk.microservice.sskx.microapp.enums.MicroServiceCodeEnum;
import com.dftcmedia.tckk.microservice.sskx.microapp.exception.MicroException;
import com.dftcmedia.tckk.microservice.sskx.microapp.service.SensitivewordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Component
@Slf4j
public class UploadMediaIdUtil {
@Resource
private SensitivewordsService sensitivewordsService;
public String uploadMedia(){
JSONObject jsonObject = uploadImage(“图片资源的URL”);
if(jsonObject==null|| StringUtils.isBlank(jsonObject.getString("media_id"))){
log.error("上传素材库"+jsonObject);
throw new MicroException(MicroServiceCodeEnum.TARGET_NOT_EXIST);
}
return jsonObject.getString("media_id");
}
private JSONObject uploadImage(String mediaUrl) {
//此处是获取微信小程序的AccessToken 前几篇文章对如何获取有专门说明,此处就不再赘述
String accessToken = sensitivewordsService.getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type=image";
try{
byte[] file = getFile(mediaUrl);
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost request = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("media", file, ContentType.DEFAULT_BINARY, "1.jpg");
HttpEntity entity = builder.build();
request.setEntity(entity);
HttpResponse resp = httpclient.execute(request);
HttpEntity httpEntity = resp.getEntity();
String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
JSONObject jso = JSONObject.parseObject(result);
log.info("上传临时素材结果:"+jso);
return jso;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private static byte[] getFile(String url) throws IOException{
URL urlConet = new URL(url);
HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(4 * 1000);
InputStream inStream = con .getInputStream(); //通过输入流获取图片数据
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
byte[] data = outStream.toByteArray();
return data;
}
}