首页 > 其他 > 详细

02 流的方式预览文件

时间:2016-08-31 15:29:52      阅读:127      评论:0      收藏:0      [点我收藏+]

  页面预览文件的时候,避免暴露服务器目标文件的所在地址,而是通过一个请求,把文件流直接输出展示。

    /**
     * 读取文件
     * 
     * @param request
     * @param response
     * @param path
     */
    @RequestMapping(value = "/readFile", method = {RequestMethod.POST,RequestMethod.GET})
    public void readFile(HttpServletRequest request, HttpServletResponse response, Long id) {

        response.reset();

        InputStream in = null;
        OutputStream output = null;
     try {

            //调用ServletOutputStream或者Writer之前有效。
            //当使用的缓存已满时,容器必须立刻刷新把缓存的内容发送到客户端,如果这是第一个被发送到客户端的数据,那么response也会被认为是已提交
            File file = new File(ctxPath + File.separator + fileName);
            
            //输出文件流
            if (file.exists()) {
                output = response.getOutputStream();
                in = new FileInputStream(file);
                byte tmp[] = new byte[256];
                int i = 0;
                while ((i = in.read(tmp)) != -1) {
                    output.write(tmp, 0, i);
                }
                output.flush();
            }
        
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != output) {
                    output.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

02 流的方式预览文件

原文:http://www.cnblogs.com/meitanzai/p/5825792.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!