当前位置:首页 » 文件管理 » 微信上传文件接口

微信上传文件接口

发布时间: 2023-05-24 01:28:24

‘壹’ 微信开发平台中有个接口是上传多媒体文件,我用的是java 开发的,我怎么样才能在后台实现呢代码如下:

/**
*文件上传到微信服务器
*@paramfileType文件类型
*@paramfilePath文件路径
*@returnJSONObject
*@throwsException
*/
publicstaticJSONObjectsend(StringfileType,StringfilePath)throwsException{
Stringresult=null;
Filefile=newFile(filePath);
if(!file.exists()||!file.isFile()){
thrownewIOException("文件不存在");
}
/**
*第一部分
*/
URLurlObj=newURL("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+getAccess_token()+"&type="+fileType+"");
HttpURLConnectioncon=(HttpURLConnection)urlObj.openConnection();
con.setRequestMethod("POST");//以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);//post方式不能使用缓存
//设置请求头信息
con.setRequestProperty("Connection","Keep-Alive");
con.setRequestProperty("Charset","UTF-8");
//设置边界
StringBOUNDARY="----------"+System.currentTimeMillis();
con.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY);
//请求正文信息
//第一部分:
StringBuildersb=newStringBuilder();
sb.append("--");//必须多两道线
sb.append(BOUNDARY);
sb.append(" ");
sb.append("Content-Disposition:form-data;name="file";filename=""+file.getName()+"" ");
sb.append("Content-Type:application/octet-stream ");
byte[]head=sb.toString().getBytes("utf-8");
//获得输出流
OutputStreamout=newDataOutputStream(con.getOutputStream());
//输出表头
out.write(head);
//文件正文部分
//把文件已流文件的方式推入到url中
DataInputStreamin=newDataInputStream(newFileInputStream(file));
intbytes=0;
byte[]bufferOut=newbyte[1024];
while((bytes=in.read(bufferOut))!=-1){
out.write(bufferOut,0,bytes);
}
in.close();
//结尾部分
byte[]foot=(" --"+BOUNDARY+"-- ").getBytes("utf-8");//定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBufferbuffer=newStringBuffer();
BufferedReaderreader=null;
try{
//定义BufferedReader输入流来读取URL的响应
reader=newBufferedReader(newInputStreamReader(con.getInputStream()));
Stringline=null;
while((line=reader.readLine())!=null){
//System.out.println(line);
buffer.append(line);
}
if(result==null){
result=buffer.toString();
}
}catch(IOExceptione){
System.out.println("发送POST请求出现异常!"+e);
e.printStackTrace();
thrownewIOException("数据读取异常");
}finally{
if(reader!=null){
reader.close();
}
}
JSONObjectjsonObj=newJSONObject(result);
returnjsonObj;
}

‘贰’ 如何向微信服务器上传文件

在某些开发中,我们需要向微信服务器发送文件,比如图片,语音等等,借助微信服务器来实现我们的一些需求,具体的实现如下:

/**
* 向微信服务器上传文件
*
* @param accessToken
* 进入的接口
* @param type
* 文件类型(语音或者是图片)(对于文档不适合)
* @param url
* 文件的存储路径
* @return json的格式{"media_id":
* "nrSKG2eY1E__pdiNiSXuijbCmWWc8unzBQ"
* ,"created_at":1408436207,"type":"image"}
*/
public JSONObject uploadFile(String fileType, String filePath)
throws Exception {
GetExistAccessToken getExistAccessToken = GetExistAccessToken.getInstance();
String accessToken = getExistAccessToken.getExistAccessToken();
// 上传文件请求路径
String action = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="
+ accessToken + "&type=" + fileType;
URL url = new URL(action);
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("上传的文件不存在");
}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.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=\"file\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
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;
try {
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con
.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if (reader != null) {
reader.close();
}
}
JSONObject jsonObj = new JSONObject(result);
return jsonObj;
}

‘叁’ 微信小程序-上传文件 (chooseMessageFile)

微信液铅小程序有 wx.chooseImage 方法选择图片,但是想选择文件,chooseFile这种接早嫌口却没有提供。

还好提供陆埋手了其它方法

到微信的消息栏选择文件助手后

参考
https://developers.weixin.qq.com/community/develop/doc/
https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html

热点内容
洛奇合成脚本 发布:2025-02-08 22:57:04 浏览:141
linux文件软链接 发布:2025-02-08 22:35:48 浏览:773
iphone6s缓存怎么清理 发布:2025-02-08 22:33:17 浏览:928
数据库系统设计的步骤 发布:2025-02-08 22:11:19 浏览:44
processc语言 发布:2025-02-08 22:11:15 浏览:537
国产车配置为什么这么便宜 发布:2025-02-08 22:09:52 浏览:481
服务器为什么需要专线 发布:2025-02-08 22:07:27 浏览:872
java正则表达式正则替换 发布:2025-02-08 22:01:04 浏览:506
服务器不识别配置的ip地址 发布:2025-02-08 22:00:02 浏览:615
橙云服务器 发布:2025-02-08 21:59:48 浏览:438