第十二章节-下载文件

图片或者HTML文件这样的静态资源 ,在浏览器中打开 正确的URL就可以下载,只要资源是放在应用程序的目录下面,或者是应用程序的子目录下面,而不是放在WEB-INF下,Servlet/jsp容器就

会将这个资源发送到浏览器。然而,有时候静态资源是保存一应用程序目录以外或者是数据库中,则要通过编程来发送资源。

例子

  • 工程目录 

  • ResourceController
@Controller
public class ResourceController {
	private static final Log logger = LogFactory.getLog(ResourceController.class );
	
	@RequestMapping(value ="/login")
	public String login(@ModelAttribute Login login, HttpSession session, Model model){
		model.addAttribute("login" , new Login()) ; // for what 
		if ("lsj".equals(login.getUserName())&& "123".equals(login.getPassword())){
			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 dataDir= request.getServletContext().getRealPath("/WEB-INF/data") ;
		File file = new File(dataDir , "secret.pdf") ;
		if (file.exists()){
			response.setContentType("application/pdf");
			response.addHeader("Content-Disposition", 
					"attachment; filename=secret.pdf");
			byte [] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			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 (Exception e) {
				e.printStackTrace();
			}finally{
				if (bis!= null){
					try {
						bis.close();
					} catch (IOException e2) {
						
					}
				}
				if (fis!= null){
					try {
						fis.close();
					} catch (IOException e2) {
				
					}
				}
			}
		}
		return null;//不进行跳转
	}
}
  • Login
public class Login  implements Serializable {
    private static final long serialVersionUID = -38L;

    private String userName;
    private String password;
    
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
  • LoginForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
<form:form commandName="login" action="login" method="post">
    <fieldset>
        <legend>Login</legend>
        <p>
            <label for="userName">User Name: </label>
            <form:input id="userName" path="userName" cssErrorClass="error"/>
        </p>
        <p>
            <label for="password">Password: </label>
            <form:password id="password" path="password" cssErrorClass="error"/>
        </p>
        <p id="buttons">
            <input id="reset" type="reset" tabindex="4">
            <input id="submit" type="submit" tabindex="5" 
                value="Login">
        </p>
    </fieldset>
</form:form>
</div>
</body>
</html>
  • Main.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Download Page</title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
    <h4>Please click the link below.</h4>
    <p>
        <a href="resource_download">Download</a>
    </p>
</div>
</body>
</html>

  

  

  

原文地址:https://www.cnblogs.com/chuiyuan/p/4623306.html