kkFilrView(三)关键代码分析(2)

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服务器的文件中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值