微信企业号上传媒体文件之服务器文件上传
企业在使用接口时,对多媒体文件、多媒体消息的获取和调用等操作,是通过media_id来进行的。
通过接口https://qyapi./cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE,企业可以上传多媒体文件。
注意,每个多媒体文件(media_id)会在上传到微信服务器3天后自动删除,以节省服务器资源。
通常文件上传是通过html表单进行的,通过HttpURLConnection 可以不经过浏览器直接在服务器端进行表单的POST提交,完成文件上传功能!
需要注意的是,文件名必须是完整的绝对路径。
如在windows 环境下:D:\\file\\123我是一个中午名称的文件.docx
简单流程描述:
1.定义数据分隔线 (boundary分割参数,长度建议10位以上)。
2.与微信服务器建立链接(HttpURLConnection)
3.获取上传文件输出流,准备往微信服务器写数据
4.构造请求体等相关参数开始向微信服务器写数据(form-data中媒体文件标识,有filename、filelength、content-type等信息,其中file的表单名称为media )。
5.读取上传文件后微信服务器返回的内容,并用json解析并返回(定义BufferedReader输入流来读取URL的响应)
具体实现代码:
package org.oms.qiye;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import .HttpURLConnection;
import .URL;
import net.sf.json.JSONObject;
public class WXUpload {
private static final String upload_wechat_url = "https://qyapi./cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
public static JSONObject upload(String accessToken, String type, String fileUrl) {
JSONObject jsonObject = null;
String last_wechat_url = upload_wechat_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
// 定义数据分割符
String boundary = "----------sunlight";
try {
URL uploadUrl = new URL(last_wechat_url);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
URL mediaUrl = new URL(fileUrl);
HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
meidaConn.setDoOutput(true);
meidaConn.setRequestMethod("GET");
// 从请求头中获取内容类型
String contentType = meidaConn.getHeaderField("Content-Type");
String filename=getFileName(fileUrl,contentType);
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", filename).getBytes());
outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
byte[] buf = new byte[1024 * 8];
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();
// 使用json解析
jsonObject = JSONObject.fromObject(buffer.toString());
System.out.println(jsonObject);
} catch (Exception e) {
System.out.println("上传文件失败!");
e.printStackTrace();
}
return jsonObject;
}
public static String getFileName(String fileUrl,String contentType) {
String filename="";
if (fileUrl != null && !"".equals(fileUrl)) {
if(fileUrl.contains(".")){
filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
}else{
if(contentType==null || "".equals(contentType)){
return "";
}
String fileExt="";
if ("image/jpeg".equals(contentType)) {
fileExt = ".jpg";
} else if ("audio/mpeg".equals(contentType)) {
fileExt = ".mp3";
} else if ("audio/amr".equals(contentType)) {
fileExt = ".amr";
} else if ("video/mp4".equals(contentType)) {
fileExt = ".mp4";
} else if ("video/mpeg4".equals(contentType)) {
fileExt = ".mp4";
} else if ("text/plain".equals(contentType)) {
fileExt = ".txt";
} else if ("text/xml".equals(contentType)) {
fileExt = ".xml";
} else if ("application/pdf".equals(contentType)) {
fileExt = ".pdf";
} else if ("application/msword".equals(contentType)) {
fileExt = ".doc";
} else if ("application/vnd.ms-powerpoint".equals(contentType)) {
fileExt = ".ppt";
} else if ("application/vnd.ms-excel".equals(contentType)) {
fileExt = ".xls";
}
filename="Media文件"+fileExt;
}
}
return filename;
}
}
以上就是微信企业号上传自己服务器文件到微信服务器的方法,此方法中文文件名称不会乱码!
转载请注明出处,以免惨不忍睹!
技术交流请加入QQ群:点击链接加入群【微信企业号开发交流】:/?_wv=1027&k=RgbtOX