public ResultResp uploadmaterial(HttpServletRequest request) throws Exception {
WxMaterialType materialType = WxMaterialType.valueOf(request.getParameter("materialtype"));
String csid = request.getParameter("csid");
String cropType = request.getParameter("croptype");
String appid = request.getParameter("appid");
String realAppid = sysWxBindCorpService.getMpAppIdByCsid(csid, cropType);
if (StringUtils.isNotEmpty(appid) && appid.equals(realAppid)) {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
if (multiRequest.getFileMap() == null || multiRequest.getFileMap().size() <= 0) {
return new ResultFailure("請選擇上傳文件");
}
Iterator<?> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
List<MultipartFile> files = multiRequest.getFiles(iter.next().toString());
MultipartFile file = files.get(0);
if (file != null && StringUtils.isNotEmpty(file.getOriginalFilename())) {
String filename = file.getOriginalFilename();
long filelength = file.getSize();
InputStream input = file.getInputStream();
String data = weChatMaterialUpload.uploadmaterial(appid, materialType, input, filename, filelength);
JSONObject jsonObject = JSONObject.parseObject(data);
if (jsonObject != null && StringUtils.isNotEmpty(jsonObject.getString("media_id")))
return new ResultSuccess(jsonObject.getString("url"));
else
return new ResultFailure(data);
}
}
return new ResultFailure("無效的文件");
} else {
return new ResultFailure("請選擇上傳文件");
}
} else {
return new ResultFailure("appid驗證失敗");
}
}
public String uploadmaterial(String appid, WxMaterialType materialType, InputStream sbs, String filename, long filelength) {
try {
String url = materialType.getType().equals("txtimg") ? UPLOAD_IMG_URL : ADD_MATERIAL_URL;
url = MessageFormat.format(url, accessToken.getAccessToken(appid));
String result = WeChatHttpUtil.Instance().uploadMaterial(url, new DataInputStream(sbs), Long.toString(filelength), filename, materialType.getType());
logger.info("uploadimg上傳圖文素材內圖片返回:" + result);
JSONObject jsonObject = WeChatRequest.analysisValue(result);
if (jsonObject != null && jsonObject.containsKey("errcode") && (jsonObject.get("errcode").equals(40001) || jsonObject.get("errcode").equals(42001)
|| jsonObject.get("errcode").equals(41001) || jsonObject.get("errcode").equals(40014))) {
// 清除微信token緩存並重試請求
WxTokenCache.setAccessToken(appid, "");
result = WeChatHttpUtil.Instance().uploadMaterial(url, new DataInputStream(sbs), Long.toString(filelength), filename, materialType.getType());
}
logger.info("uploadimg上傳圖文素材內圖片返回:" + result);
return result;
} catch (Exception e) {
logger.error("uploadimg:" + e.getMessage());
e.printStackTrace();
return e.toString();
}
}
public String uploadMaterial(String url,DataInputStream in,String filelength,String filename, String type) throws Exception {
try {
url = url.replace("TYPE", type);
URL urlObj = new URL(url);
// 創建Http連接
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false); // 使用post提交需要設置忽略緩存
// 消息請求頭信息
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=\"media\";filename=\"" + filename + "\";filelength=\"" + filelength + "\"\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 ByteArrayInputStream(byts.getBytes(CharEncoding.UTF_8)));
//in=new DataInputStream(meidaConn.getInputStream());
int bytes = 0;
byte[] bufferOut = new byte[1024 * 1024 * 10]; // 10M
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
/*對類型為video的素材進行特殊處理*/
if ("video".equals(type)) {
out.write(("--" + BOUNDARY + "\r\n").getBytes());
out.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
out.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", filename, "miaoshu").getBytes());
}
in.close();
// 結尾
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
// 獲取響應
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
reader.close();
}
logger.info("uploadMaterial-result:" + result);
return result;
} catch (Exception e) {
logger.error("uploadMaterial-ex:" + e.getMessage());
throw e;
}
}
public enum WxMaterialType {
WX_MATERIALTYPE_NEWS("news"), // 圖文
WX_MATERIALTYPE_IMAGE("image"), // 圖片
WX_MATERIALTYPE_VOICE("voice"), // 語音
WX_MATERIALTYPE_VIDEO("video"),// 視頻
WX_MATERIALTYPE_IMG("txtimg");//圖文中的圖片,僅在上傳圖文消息內的圖片獲取URL時使用
private String type;
WxMaterialType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}