Micro-channel material uploaded (JAVA)

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 ( "Invalid file");

The else {}
return new new ResultFailure ( "Please select the file upload");
}
} the else {
return new new ResultFailure ( "AppID verification failed");
}

}

 

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))) {

// Clear micro-channel and retry the token request buffer
WxTokenCache.setAccessToken (appid, "");

result = WeChatHttpUtil.Instance().uploadMaterial(url, new DataInputStream(sbs), Long.toString(filelength), filename, materialType.getType());
}

logger.info ( "the creative graphic image upload uploadimg Returns:" Result +);
return Result;
} the 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 // Create connection
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection ();
conn.setRequestMethod ( "POST");
conn.setDoInput (to true);
conn.setDoOutput (to true);
conn.setUseCaches (false); // use post submission needs to be set to ignore the cache

// 消息请求头信息
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");

// create output stream
the OutputStream the DataOutputStream new new OUT = (conn.getOutputStream ());
// obtain an output stream header
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"), // Photo
WX_MATERIALTYPE_IMAGE ( "image"), // Pictures
WX_MATERIALTYPE_VOICE ( "voice"), // voice
WX_MATERIALTYPE_VIDEO ( "video"), // video

WX_MATERIALTYPE_IMG ( "txtimg"); // graphic pictures, URL used to obtain only upload pictures in a graphic message

private String type;

WxMaterialType(String type) {
this.type = type;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}
}

Guess you like

Origin www.cnblogs.com/chuntao/p/11433324.html