微信端文件上传和下载

来源:互联网 发布:csolfps优化大全 编辑:程序博客网 时间:2024/05/29 19:58

最近微信开发,用到文件上传和下载,代码整来,共享下。

public static String downLoadMedia(String download,String access_token,String mediaId,String format,String realPath) {
// 微信端多媒体文件下载
/*String upload = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
String download = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";*/
String downloadMediaUrl = String.format(download,access_token,mediaId);
logger.info("微信多媒体文件下载地址:"+downloadMediaUrl);
try {
URL downloadUrl = new URL(downloadMediaUrl);
InputStream inputStream = downloadUrl.openStream();
String weChatMediaPath = PropKit.get("weChatMediaPath");
String fileName = realPath+weChatMediaPath+DateUtils.dateStr3(new Date())+"."+format;
File file = new File(fileName);//微信端多媒体文件下载存放路径
logger.info("微信多媒体文件路径:"+fileName);
if(!file.exists()){
file.getParentFile().mkdirs();
}
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[1024*8];
int len = 0;
while((len = inputStream.read(buf)) != -1) {
outputStream.write(buf,0,len);
}
outputStream.close();
inputStream.close();
return weChatMediaPath+DateUtils.dateStr3(new Date())+"."+format;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}


下面是 上传

/**
* 上传
* @param token
* @param string
* @param picpath
* @return
*/
//String upload = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+ACCESS_TOKEN+"&type=%s";三天后自动删除
//https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN  post请求
//https://api.weixin.qq.com/cgi-bin/material/add_material?access_token="+ACCESS_TOKEN+"&type=%s" 占用使用次数
public static JSONObject upLoadMedia(String url,String mediaType,String mediaPath) {
String uploadMediaUrl = String.format(url,mediaType);
String boundary = "----------" + System.currentTimeMillis();// 设置边界  
try {
URL uploadUrl = new URL(uploadMediaUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type","/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)

OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(mediaPath);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");


// 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileType = FileType.getFileType(mediaPath);
logger.info("当前上传多媒体类型为:"+fileType);
if(fileType == null) {
throw new BussinessException("微信端获取多媒体类型出错请联系系统管理员!");
}
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n",fileType).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n",contentType).getBytes());

// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
meidaConn.disconnect();


// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
uploadConn.disconnect();
//解析返回结果
JSONObject jsonObject = JSON.parseObject(buffer.toString());
logger.info("上传多媒体文件返回信息:"+jsonObject.toJSONString());
return jsonObject;
} catch (Exception e) {
String error = String.format("上传媒体文件失败:%s", e);
System.out.println(error);

return null;
}


0 0