上传临时素材总是invalid file type?
上传部分代码如下
String urlString="https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+token+"&type="+fileType;
URL url=new URL(urlString);
HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");//以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=\"" + file.getName() + "\"; filelength=\""
+ file.length() + "\"\r\n");
sb.append("content-type:application/octet-stream\r\n\r\n");
System.out.println("sb:"+sb);
//获得输出流
OutputStream out=new DataOutputStream(conn.getOutputStream());
//输出表头
out.write(sb.toString().getBytes("UTF-8"));
//文件正文部分
//把文件以流的方式 推送道URL中
DataInputStream din=new DataInputStream(new FileInputStream(file));
int bytes=0;
byte[] buffer=new byte[1024];
while((bytes=din.read(buffer))!=-1){
out.write(buffer,0,bytes);
}
din.close();
//结尾部分
byte[] foot=("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
out.write(foot);
out.flush();
out.close();