2021SC@SDUSC
(一)仅针对图片的文件预览
/**
* 文件预览 仅针对图片
* @param model
* @param req
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "picturesPreview")
public String picturesPreview(Model model, HttpServletRequest req) throws UnsupportedEncodingException {
String urls = req.getParameter("urls");
String currentUrl = req.getParameter("currentUrl");
logger.info("预览文件url:{},urls:{}", currentUrl, urls);
// 路径转码
String decodedUrl = URLDecoder.decode(urls, "utf-8");
String decodedCurrentUrl = URLDecoder.decode(currentUrl, "utf-8");
// 抽取文件并返回文件列表
String[] imgs = decodedUrl.split("\\|");
List imgurls = Arrays.asList(imgs);
model.addAttribute("imgurls", imgurls);
model.addAttribute("currentUrl",decodedCurrentUrl);
return "picture";
}
先将图片的路径转码,用URLDecoder类的decode()方法。
URLEncoder.encode(String s, String enc):使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式。
URLDecoder.decode(String s, String enc):使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码。
用指定的编码格式进行编码、解码,可以保证不会出现乱码。这两个方法主要用来解决http get请求不能传输中文参数问题。http请求是不接受中文参数的。发送方将中文参数encode,接收方将参数decode,就能收到准确的原始字符。
通过Arrays.asList方法将文件返回列表。
model.addAttribute()方法 往前台传数据,图片信息。
(二)对跨域问题文件的解决
/**
* 根据url获取文件内容
* 当pdfjs读取存在跨域问题的文件时将通过此接口读取
*
* @param urlPath url
* @param response response
*/
@RequestMapping(value = "/getCorsFile", method = RequestMethod.GET)
public void getCorsFile(String urlPath, HttpServletResponse response) {
logger.info("下载跨域pdf文件url:{}", urlPath);
try {
downloadUtils.saveToOutputStreamFromUrl(urlPath, response.getOutputStream());
} catch (IOException e) {
logger.error("下载跨域pdf文件异常,url:{}", urlPath, e);
}
}
downloadUtils中的方法:
public boolean saveToOutputStreamFromUrl(String urlStr, OutputStream os) throws IOException {
// 1. 获取url对应的流
InputStream is = getInputStreamFromUrl(urlStr);
if (is != null) {
copyStream(is, os);
} else {
urlStr = URLUtil.normalize(urlStr, true, true);
is = getInputStreamFromUrl(urlStr);
if (is != null) {
copyStream(is, os);
} else {
os.close();
return false;
}
}
return true;
}
获取url对应的流,再将远程端文件以流的形式写入kkfile服务器的文件中。