springmvc中使用文件下載功能


項目代碼:https://github.com/PeiranZhang/springmvc-fileupload

使用文件下載步驟

  • 對請求處理方法使用void或null作為返回類型,並在方法中添加HttpServletResponse參數
  • 將響應的內容類型設為文件的內容類型
  • 添加一個名為Content-Disposition的HTTP響應標題,並賦值attachment; filename= fileName,這里的fileName是默認文件名,應該出現在File Download(文件下載)對話框中。它通常與文件同名,但是也並非一定如此。(可選)

例子:下載服務器上的pdf文件

指定用戶、密碼登錄表單之后,設置session,然后才可以下載文件:/WEB-INF/data/secret.pdf

Controller代碼

@Controller
public class ResourceController {

private static final Log logger = LogFactory.getLog(ResourceController.class);

/**
 * @param login @ModelAttribute 注解接受表單中的login對象
 * @param session
 * @param model
 * @return
 */
@RequestMapping(value="/login")
public String login(@ModelAttribute Login login, HttpSession session, Model model) {
    System.out.println(login);
    //與jsp中的標簽綁定
    model.addAttribute("login", new Login());
    if ("paul".equals(login.getUserName()) &&
            "secret".equals(login.getPassword())) {
        //設置session
        session.setAttribute("loggedIn", Boolean.TRUE);
        return "Main";
    } else {
        return "LoginForm";
    }
}

@RequestMapping(value="/resource_download")
public String downloadResource(HttpSession session, HttpServletRequest request,
        HttpServletResponse response) {
    if (session == null || 
            session.getAttribute("loggedIn") == null) {
        return "LoginForm";
    }
    String dataDirectory = request.
            getServletContext().getRealPath("/WEB-INF/data");
    System.out.println(dataDirectory);
    File file = new File(dataDirectory, "secret.pdf");
    if (file.exists()) {
        //設置響應類型,這里是下載pdf文件
        response.setContentType("application/pdf");
        //設置Content-Disposition,設置attachment,瀏覽器會激活文件下載框;filename指定下載后默認保存的文件名
        //不設置Content-Disposition的話,文件會在瀏覽器內打卡,比如txt、img文件
        response.addHeader("Content-Disposition",
                "attachment; filename=secret.pdf");
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        // if using Java 7, use try-with-resources
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (IOException ex) {
            // do something, 
            // probably forward to an Error page
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return null;
}

}

LoginForm.jsp

LoginFom.jsp

Main.jsp

Main.jsp

結果

登錄

下載

例子:瀏覽器內顯示圖片。圖片放在WEN-INF目錄下面,可以禁止直接請求

Controller代碼

@Controller
public class ImageController {

private static final Log logger = LogFactory.getLog(ImageController.class);

@RequestMapping(value="/image_get/{id}", method = RequestMethod.GET)
public void getImage(@PathVariable String id, 
        HttpServletRequest request, 
        HttpServletResponse response, 
        @RequestHeader String referer) {
    //referer記錄了該請求是從哪個鏈接過來的,可以用來判斷請求是否合法
    if (referer != null) {
        System.out.println(referer);
        String imageDirectory = request.getServletContext().
                getRealPath("/WEB-INF/image");
        File file = new File(imageDirectory, 
                id + ".jpg");
        if (file.exists()) {
            response.setContentType("image/jpg");
            //不設置Content-Disposition的,圖像在瀏覽器內打卡
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            // if you're using Java 7, use try-with-resources
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (IOException ex) {
                // do something here
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        
                    }
                }
            }
        }
    }
}
}

html文件

html文件

結果

直接請求html文件,html里面的img標簽的src記錄了請求地址,發出請求,后台控制,將圖片的內容輸出到瀏覽器上

結果

參考

  • 《JSP、Servlet和SpringMVC學習指南》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM