SpringMVC下载word(非poi)

   /**
     * 下载文件功能
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("download.action")
    public void doDownload( HttpServletRequest request, HttpServletResponse response, Map<String, Object> model) {
        try {
            // 获得请求文件名
            String filename = request.getParameter("filename");
            System.out.println(filename);

            // 设置文件MIME类型
            // response.setContentType(getServletContext().getMimeType(filename));
            response.setContentType(new MimetypesFileTypeMap().getContentType(filename));
            // 设置Content-Disposition
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            // 读取目标文件,通过response将目标文件写到客户端
            // 获取目标文件的绝对路径
            //D:/temp/partinUploadFiles/
            //String fullFileName = request.getSession().getServletContext().getRealPath("/download/" + filename);
            String fullFileName="D:/temp/partinUploadFiles/"+filename;
            // System.out.println(fullFileName);
            // 读取文件
            InputStream in = new FileInputStream(fullFileName);
            OutputStream out = response.getOutputStream();

            // 写文件
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }

            in.close();
            out.close();
        } catch (Exception e) {
            try {
                response.sendRedirect("wenjianerror.jsp");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }  

猜你喜欢

转载自blog.csdn.net/SicongFu/article/details/78060843
今日推荐