微信上传素材 java_微信素材上传(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 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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值