简体   繁体   English

Struts2中的动态文件下载

[英]Dynamic file download in Struts2

In my Struts2 application, i have the page that list of file names, cliking on that filename will download that file.here filename comes from db. 在我的Struts2应用程序中,我在页面上找到文件名列表,单击该文件名即可下载该文件。此处文件名来自db。 for that i have coded like 为此,我编码像

<iterator list... 
<a href="filedownload.action?filepath=${filepath}>${filepath} </a>
</iterator...

in filedownload action i have written codes open filestream (struts2 filedownalod). 在文件下载操作中,我编写了打开文件流的代码(struts2 filedownalod)。

It is working in all browsers except Firefox7+. 它可以在除Firefox7 +之外的所有浏览器中使用。 its throwing **"Content correpted Error"** . 其抛出**"Content correpted Error"**

I think it has some issue with URL encoding. 我认为网址编码存在一些问题。 I don't think it is good idea to pass path as parameter. 我认为将路径作为参数传递不是一个好主意。 It is safe to pass ID on the database to the action and download by FileInputStream. 将数据库上的ID传递给操作并由FileInputStream下载是安全的。 At least, you can check permission of user when it is about to download privileged files. 至少,要下载特权文件时,您可以检查用户的权限。

I would do like this: 我会这样:

<iterator list... 
<a href="filedownload?id=%{id_in_the_database} </a>
</iterator...

Action class 动作课

public String download() throws Exception {

    fileName = getFromDatabaseById(id);

    try
    {
        fileInputStream = new FileInputStream(new File(FILE_FOLDER + filename));
    }
    catch(FileNotFoundException ex)
    {
        logger.error(this.getClass().getSimpleName() + ": File in " + FILE_FOLDER + filename + " cannot be found.");
            return ERROR;
        }

        return DOWNLOAD;
}

And in your struts.xml 并在您的struts.xml中

 <action name="filedownload" method="download" class="com.yourproject.filedownload">
    <result name="download" type="stream">
      <param name="contentType">application/octet-stream</param>
      <param name="inputName">fileInputStream</param>
      <param name="contentDisposition">attachment;filename=%{filename}</param>
      <param name="bufferSize">4096</param>
    </result>
    <result name="error" type="redirectAction">erroraction</result>
 </action>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM