springcloud 通过后端去下载和预览文件,要重设跨域允许

Posted 不负前行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud 通过后端去下载和预览文件,要重设跨域允许相关的知识,希望对你有一定的参考价值。

@RequestMapping("/download")
    public void downloadNet(String uri, boolean isOnLine, HttpServletResponse response) throws MalformedURLException {

        // 下载网络文件
        InputStream inStream = null;
        OutputStream fs = null;

        URL url = new URL(uri);
        String filename = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            URLConnection conn = url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
            inStream = new BufferedInputStream(conn.getInputStream());
            int len = 0;
            response.reset();
            if (isOnLine) { // 在线打开方式
                response.setContentType(conn.getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + filename);
                response.setHeader("Access-Control-Allow-Origin", cors);
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Headers", corsHeader);
                response.setHeader("Vary", "Origin");
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                response.setHeader("Access-Control-Allow-Origin", cors);
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Headers", corsHeader);
                response.setHeader("Vary", "Origin");
            }

            fs = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[1024];
            while ((len = inStream.read(buffer)) > 0)
                fs.write(buffer, 0, len);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {
                }
            }
            if (null != fs) {
                try {
                    fs.close();
                } catch (IOException e) {
                }
            }
        }
    }

 

以上是关于springcloud 通过后端去下载和预览文件,要重设跨域允许的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot框架集成FastDFS分布式文件系统,实现文件路径加密处理的图片预览下载。

C# MVC ajax上传 文件

纯前端导出表格

接口测试

java实现word转pdf在线预览(前端使用PDF.js;后端使用openofficeaspose)

vue 实现在线预览excel