zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringMVC 下载文件(直接在浏览器打开)

2023-09-11 14:15:41 时间

前端代码:

  //下载用户手册
    function downUserManual() {
        debugger
        var downLoadPath = "/system/downUserManual.do";
        var url = getRootPath() + downLoadPath;
        window.open(url)

后端代码:

@RequestMapping(value = "/downUserManual.do", method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        FileInputStream fis = null;
        byte[] bytes = null;
        ServletOutputStream ouputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            ServletContext servletContext = request.getSession().getServletContext();
            String filePath = servletContext.getRealPath("/downloadfile/用户手册.pdf");
            File file = new File(filePath);

            fis = new FileInputStream(file);
            baos = new ByteArrayOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            bytes = baos.toByteArray();
            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);
            ouputStream = response.getOutputStream();
            ouputStream.write(bytes, 0, bytes.length);
            ouputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ouputStream != null) {
                try {
                    ouputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }