我想下载一个pdf文件,该文件存储在项目的WebContent中的文件夹中 [英] I want to download a pdf file which is stored in the folder which is in WebContent of project

查看:145
本文介绍了我想下载一个pdf文件,该文件存储在项目的WebContent中的文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Strut文件.

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>

这是File对象正在获取null的操作代码.

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

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

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.

推荐答案

问题

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

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

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.

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

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()); 

在返回结果配置中使用动态参数时,需要使用吸气剂来返回stream结果.您应该提供fileName的吸气剂.

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.

这篇关于我想下载一个pdf文件,该文件存储在项目的WebContent中的文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆