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

醉酒当歌 提交于 2019-12-02 01:45:48

问题


This is my Strut file.

<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>

and this is action code where the object of File is getting 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";
        }

I have stored the file which I want to download in web content folder and I have stored the path of it in the database. I don't know what is the problem.


回答1:


The problem with

String path2=request.getParameter("path1");

This method may return null if parameter path1 is missing. If it's not null then it should be a valid path to the readable file that you application has access.

Read the example How to read file in Java – FileInputStream. You can trace the output with the code.

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

The getter is needed to return a stream result, and as you are using dynamic parameter in the result config. You should provide the getter for fileName.




回答2:


I have solved this question. I have stored the physical path of the file in the data base.For example if your project path is : D:/Workspace_ABC/SampleProject/WebContent/D-Files/APJ.AbdulKalam.pdf then store this path as it is in the database table. and then use this path to download file.



来源:https://stackoverflow.com/questions/37028702/i-want-to-download-a-pdf-file-which-is-stored-in-the-folder-which-is-in-webconte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!