0 问题描述
- 开发企信自建应用时需要用到微盘文件下载功能,调用接口后发现返回的是一个资源链接,而且资源有效期为2个小时,且访问时需要带着cookie。所以想到下载下来,将资源上传到我们自己的服务器上,以方便预览等。
1 根据企信官方文档调用下载链接拿到文件地址和cookie值
下图为企信官方文档截图,获取文件链接见官方文档
2. 根据企信返回的download_url、cookie_name、cookie_value获取文件资源,上传服务器并返回链接给前端
示例代码:
private JSONObject downloadWeiPanFile(JSONObject jsonObject) {
// 调用企信-微盘-文件下载接口返回的资源地址
String url = jsonObject.getString("download_url");
// 调用企信-微盘-文件下载接口返回的cookie值
String cookieValue = jsonObject.getString("cookie_name") + "=" + jsonObject.getString("cookie_value");
try {
// 从链接中截取文件名
String[] split = url.split("filename=");
String encode = URLDecoder.decode(split[1], "UTF-8");
//new一个URL对象
URL connection = new URL(url);
//打开链接
HttpURLConnection conn = (HttpURLConnection) connection.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(20 * 1000);
// 根据企信的要求访问资源需要带着cookie值
conn.setRequestProperty("Cookie", cookieValue);
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
FileItem fileItem = this.createFileItem(inStream, encode);
MultipartFile file = new CommonsMultipartFile(fileItem);
// 上传文件路径
String filePath = "自己定义的上传文件的路径儿";
// 上传并返回新文件名称
String fileName = null;
// 系统自定义的上传方法,可根据自己系统情况做修改
fileName = FileUploadUtils.upload(filePath, file);
String url1 = fileName;
// 返回上传后文件的路径给前端
JSONObject resObj = new JSONObject();
resObj.put("url", url1);
resObj.put("fileName", fileName);
resObj.put("newFileName", FileUtils.getName(fileName));
resObj.put("originalFilename", file.getOriginalFilename());
return resObj;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
将字节流转化为:org.apache.commons.fileupload.FileItem
public FileItem createFileItem(InputStream inputStream, String fileName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";
FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
int bytesRead = 0;
byte[] buffer = new byte[99999];
OutputStream os = null;
//使用输出流输出输入流的字节
try {
os = item.getOutputStream();
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
inputStream.close();
} catch (IOException e) {
log.error("Stream copy exception", e);
throw new IllegalArgumentException("文件上传失败");
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("Stream close exception", e);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("Stream close exception", e);
}
}
}
return item;
}
3.总结
- 不能直接存储企信返回的文件链接,有效期为2个小时
- 前端直接访问企信的资源链接会出现跨域的问题,考虑后端来做
- 后端做的思路:
1.访问企信文件资源
2.获取到字节流
3.转化为MultipartFile,并上传到服务器
4.构造出新的文件资源链接返回给前端
5.前端基于新的链接提交数据即可