微信公众号之上传图片(本地和网络)
前言
Github:https://github.com/HealerJean
1、Controller
/**
*
* @param strings
* @throws Exception
*/
@Value("${wechat_erweimaEmptUrl}")
private String wechat_erweimaEmptUrl;
@ApiOperation(value = "输入path生成图片",notes = "输入path生成图片",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE,
response = ResponseBean.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "filePath", value = "图片路径", paramType = "query", dataTypeClass = String.class),
@ApiImplicitParam(name = "type", value = "1 本地文件路径 2、网络图片路径", paramType = "query", dataType = "int"),
@ApiImplicitParam(name = "weChatBusinessNoId", value = "数据库中存放微信运营者的,主键,服务区号哆趣商城 3: ",paramType = "query", dataType = "long")
})
@PostMapping("/image/creteImage")
@ResponseBody
public ResponseBean creteImage(String filePath,Integer type,Long weChatBusinessNoId){
FileOutputStream outputStream = null;
File file = null;
try {
if(type==2){
file = new File(wechat_erweimaEmptUrl+UUIDGenerator.generate()+ ".jpg");
outputStream = new FileOutputStream(file);
URL u = new URL(filePath);
BufferedImage imageQR = ImageIO.read(u);
ImageIO.write(imageQR, "jpg", outputStream);
}else {
file = new File(filePath);
}
return ResponseBean.buildSuccess(WeChatUploadUtil.uploadMediaToWXGetMedia(file, WeChatBusinessNoUtil.findById(weChatBusinessNoId)));
} catch (AppException e) {
log.error(e.getMessage(),e);
return ResponseBean.buildFailure(e.getCode(),e.getMessage());
} catch (Exception e) {
log.error(e.getMessage(),e);
return ResponseBean.buildFailure(e.getMessage());
}finally {//关闭不必要的连接
try {
if (outputStream != null) {
outputStream.close();
}
//图片生成将服务器文件删除
if(type==2){
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、上传代码
package com.duodian.youhui.admin.utils.wechat;
import com.duodian.youhui.admin.constants.WechatApiUrlParams;
import com.duodian.youhui.admin.constants.WechatMenuParams;
import com.duodian.youhui.admin.utils.wechat.AccessToakeUtil;
import com.duodian.youhui.entity.db.wechat.WeChatBusinessNo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @Desc:
* @Author HealerJean
* @Date 2018/5/28 下午3:16.
*/
@Slf4j
public class WeChatUploadUtil {
/**
*
* 作者: HealerJean
* 日期: 2018/11/7 下午1:23.
* 方法描述: type 1 本地文件路径 2、网络图片路径
*/
public static String getMedia(String filePath,Integer type,Long weChatBusinessNoId) {
FileOutputStream outputStream = null;
File file = null;
try {
if (type == 2) {
file = new File(SystemParams.WECHAT_IMAGE_EMPT_URI + StringGeneratorUtil.generate() + ".jpg");
outputStream = new FileOutputStream(file);
URL u = new URL(filePath);
Image imageTookit = Toolkit.getDefaultToolkit().createImage(u);
BufferedImage imageQR = ImageUtils.toBufferedImage(imageTookit);
// BufferedImage imageQR = ImageIO.read(u);
ImageIO.write(imageQR, "jpg", outputStream);
} else {
file = new File(filePath);
}
String accessToken = AccessToakeUtil.getAccessToaken(WeChatBusinessNoUtil.findById(weChatBusinessNoId));
return uploadMediaToWXGetMedia(file, accessToken);
}catch (AppException e) {
log.error(e.getMessage(),e);
} catch (Exception e) {
log.error(e.getMessage(),e);
}finally {//关闭不必要的连接
try {
if (outputStream != null) {
outputStream.close();
}
//图片生成将服务器文件删除
if(type==2){
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String uploadMediaToWXGetMedia(File file,String accessTtoken){
if (!file.exists()) {
log.error("文件不存在!");
return null;
}
try {
String type = "image";
String url = WechatApiUrlParams.UPLOAD__MEDIA_URL + accessTtoken + "&type=" + type + "";
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // ////////必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(head);
// 文件正文部分
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
/**
* 读取服务器响应,必须读取,否则提交不成功
*/
// 定义BufferedReader输入流来读取URL的响应
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
conn.disconnect();
log.info(buffer.toString());
String mediaId = JSONObject.fromObject(buffer.toString()).getString("media_id");
return mediaId;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
log.error("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return null;
}
/**
* 从微信服务器下载多媒体文件
*
* @author qincd
* @date Nov 6, 2014 4:32:12 PM
*/
public static String downloadMediaFromWx(String fileSavePath,String accessTtoken,String mediaId) throws IOException {
String download_media_url =WechatApiUrlParams.DOWNLOAD_MEDIA_URL;
String requestUrl = download_media_url.replace("ACCESS_TOKEN", accessTtoken).replace("MEDIA_ID", mediaId);
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
InputStream in = conn.getInputStream();
File dir = new File(fileSavePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!fileSavePath.endsWith("/")) {
fileSavePath += "/";
}
String ContentDisposition = conn.getHeaderField("Content-disposition");
String weixinServerFileName = ContentDisposition.substring(ContentDisposition.indexOf("filename")+10, ContentDisposition.length() -1);
fileSavePath += weixinServerFileName;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileSavePath));
byte[] data = new byte[1024];
int len = -1;
while ((len = in.read(data)) != -1) {
bos.write(data,0,len);
}
bos.close();
in.close();
conn.disconnect();
return fileSavePath;
}
}