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

I want to download a pdf file which is stored in the folder which is in WebContent of project

这是我的 struts.xml 文件。

<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";
        }

我已经将我要下载的文件存储在网页内容文件夹中,并将它的路径存储在数据库中。

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

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

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

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

getter 需要 return 一个 stream 结果,因为您在结果配置中使用动态参数。您应该为 fileName.

提供 getter

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