通过SpringMVC在页面下载服务器上的文件至本地磁盘

    /**
     * 下载doc文件
     *
     * @param httpServletResponse
     * @param id
     */
    @RequestMapping("/templateAction_download")
    public void downloadFile(HttpServletResponse httpServletResponse, Integer id) {
        Template template = templateService.findById(id);
        String docfilepath = template.getDocfilepath();
        //截取路径中的文件名
        String fileName = docfilepath.substring(docfilepath.lastIndexOf("\\")+1);
        try {
            //读取服务器磁盘上文件的二进制数据
            InputStream docStream = new FileInputStream(new File(docfilepath));
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[10000]; //buff用于存放循环读取的临时数据
            int rc = 0;
            while ((rc = docStream.read(buff, 0, 10000)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            //将输入流转换为字符数组输出流
            byte[] docByte = swapStream.toByteArray(); 
            //设置响应头
            httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
            httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+fileName);
            OutputStream os = httpServletResponse.getOutputStream();
            os.write(docByte);
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容