上传临时素材
Controller
@ResponseBody
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ResultVo uploadFile(
@ApiParam(value = "wxWorkInfoId", required = true) @RequestParam(value = "wxWorkInfoId") String wxWorkInfoId,
@RequestParam(value = "userId") Integer userId,
@RequestParam(value = "type") String type,
@RequestParam MultipartFile file
) {
ResultVo resultVo = new ResultVo();
String pathName = approvalFile(file);
try {
AssertUtil.asserts(StringUtils.isNotEmpty(wxWorkInfoId), "wxWorkInfoId不能为空!");
AssertUtil.asserts(userId != null, "用户Id不能为空!");
String urlType = CommonsEnum.WorkWxSecretType.APPLICATION;
String wxCorpAccessToken = wxCorpApiService.getWxCorpAccessToken(wxWorkInfoId, userId, urlType);
if (StringUtils.isNotEmpty(wxCorpAccessToken)) {
resultVo = wxCorpApiService.uploadFile(wxCorpAccessToken, type, pathName);
}
} catch (AssertException e) {
resultVo.initFailure(e.getMessage());
} catch (Exception e) {
resultVo.initFailure(e.getMessage());
} finally {
delteTempFile(new File(pathName));
}
return resultVo;
}
-----------------------------------------------------------------------
/**
* 删除本地临时文件
*/
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
public String approvalFile(MultipartFile filecontent) {
OutputStream os = null;
InputStream inputStream = null;
String fileName = null;
try {
inputStream = filecontent.getInputStream();
fileName = filecontent.getOriginalFilename();
Logger.info("fileName=" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
try {
String path = "D:\\upload\\";
// 2、保存到临时文件
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
String pathName = tempFile.getPath() + File.separator + fileName;
os = new FileOutputStream(pathName);
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}
return pathName;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Impl
public ResultVo uploadFile(String accesstoken, String fileType, String path) {
ResultVo resultVo = new ResultVo();
try {
String url = CommonsEnum.WorkWxUrl.uploadFileUrl + accesstoken + "&type=" + fileType;
String result = uploadMedia(url, new File(path), null);
Logger.info("uploadFile body:" + result);
Map resultMap = JsonUtil.readJson(result);
if (resultMap.containsKey("errcode") && !"0".equals(resultMap.get("errcode").toString())) {
String errcode = ErrorCodeManager.getMessage(resultMap.get("errcode").toString());
resultVo.initFailure(errcode);
Logger.info("uploadFile failed:" + result);
} else {
resultVo.initSuccess();
resultVo.setData(resultMap);
}
} catch (Exception e) {
resultVo.initFailure(e.getMessage());
}
return resultVo;
}
private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
/**
* 上传临时素材
*
* @param url 图片上传地址
* @param file 需要上传的文件
* @return ApiResult
* @throws IOException
*/
public static String uploadMedia(String url, File file, String params) throws IOException {
URL urlGet = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", DEFAULT_USER_AGENT);
conn.setRequestProperty("Charsert", "UTF-8");
// 定义数据分隔线
String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL";
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 定义最后数据分隔线
StringBuilder mediaData = new StringBuilder();
mediaData.append("--").append(BOUNDARY).append("\r\n");
mediaData.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
mediaData.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] mediaDatas = mediaData.toString().getBytes();
out.write(mediaDatas);
DataInputStream fs = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = fs.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
IOUtils.closeQuietly(fs);
// 多个文件时,二个文件之间加入这个
out.write("\r\n".getBytes());
if (StringUtils.isNotEmpty(params)) {
StringBuilder paramData = new StringBuilder();
paramData.append("--").append(BOUNDARY).append("\r\n");
paramData.append("Content-Disposition: form-data;name=\"description\";");
byte[] paramDatas = paramData.toString().getBytes();
out.write(paramDatas);
out.write(params.getBytes(Charsets.UTF_8));
}
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data);
out.flush();
IOUtils.closeQuietly(out);
// 定义BufferedReader输入流来读取URL的响应
InputStream in = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, Charsets.UTF_8));
String valueString = null;
StringBuffer bufferRes = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
IOUtils.closeQuietly(in);
// 关闭连接
if (conn != null) {
conn.disconnect();
}
return bufferRes.toString();
}