简体   繁体   中英

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

It is working in all browsers except Firefox7+. its throwing **"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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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