Struts 2でのファイルダウンロード

7571 ワード

struts.xmlでは次のように構成されています.
1         <action name="download" class="cn.itcast.domain.User" method="download">
2             <result type="stream" name="success">
3                 <param name="contentType">application/octet-stream</param>
4                 <param name="inputStream">inputStream</param><!--                 -->
5                 <param name="contentDisposition">attachment;filename=${filename}</param><!--         -->
6             </result>

jspページで
userはactionから伝わった
1           <c:url value="/user/download" var="url">
2               <c:param name="path" value="${user.path}"></c:param>
3               <c:param name="filename" value="${user.filename}"></c:param>
4           </c:url>
5           <a href="${url}">  </a>

User.javaで
 
 
class User{
    private String path;        //       
    private String filename;    //   
//          
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String download()
    {
        String storePath=ServletActionContext.getServletContext().getRealPath("/files");
        System.out.println("before" +path +"   "+ filename);
        //    struts2        ,     url     path, filename   
//        path=ServletActionContext.getRequest().getParameter("path");
//        filename=ServletActionContext.getRequest().getParameter("filename");
        System.out.println("after" +path +"   "+ filename);
        try {
            inputStream=new FileInputStream(storePath+"\\"+path+"\\"+filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return this.SUCCESS;
    }
}