我想下载一个pdf文件,该文件存储在项目

时间:2016-05-04 13:05:15

标签: download struts2 stream actionresult http-parameters

这是我的Strut文件。

<action name="sample" class="com.action.getPdf" method="getPdf">
    <result name="success" type="stream">
        <param name="inputName">fileInputStream</param>
       <param name="contentType">application/pdf</param>
        <param name="contentDisposition">attachment;filename="${fileName}"</param>
       <param name="bufferSize">1024</param>
    </result>
 </action>

这是File的对象获取null的动作代码。

public String getPdf()throws Exception
    {
        Session ss = HibernateUtils.getSess();
        Transaction t=ss.beginTransaction();
        HttpSession httpsession=request.getSession();
        String path2=request.getParameter("path1");
          ServletContext servletContext = ServletActionContext.getServletContext();
        //String path3=servletContext.getRealPath(path2);
        System.out.println("the relative path of  the file is:"+path2);
        try
          {

            File fileToDownload = new File(path2);   
            fileInputStream = new FileInputStream(fileToDownload);              

          }

          catch (Exception e)
          {
             if (t!=null) 
             {
                 t.rollback();
                 e.printStackTrace(); 
             }
          }
          finally 
          {
              ss.close(); 
          }


        return "success";
        }

我已将要下载的文件存储在Web内容文件夹中,并且已将其路径存储在数据库中。 我不知道这是什么问题。

2 个答案:

答案 0 :(得分:1)

的问题
String path2=request.getParameter("path1");

如果缺少参数null,此方法可能会返回path1。如果它不是null那么它应该是您的应用程序可以访问的可读文件的有效路径。

阅读示例How to read file in Java – FileInputStream。您可以使用代码跟踪输出。

System.out.println("Total file size to read (in bytes) : "
                + getFileInputStream().available()); 

需要getter来返回stream结果,并且在结果配置中使用动态参数。您应该为fileName提供getter。

答案 1 :(得分:0)

我已经解决了这个问题。我已将文件的物理路径存储在数据库中。例如,如果您的项目路径是: d:/Workspace_ABC/SampleProject/WebContent/D-Files/APJ.AbdulKalam.pdf 然后将此路径存储在数据库表中。然后使用此路径下载文件。