1. 程式人生 > >SpringMVC下載word(非poi)

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();
        }
    }