2012-08-01 57 views
5

我正在開發一個應用程序,在這裏人們將需要的文件從數據庫中提到的位置下載到他們的本地。我使用struts 2從服務器下載文件。我可以毫無例外地下載文件,並且完美地工作。 但我下載的文件有我在struts.xml中指定的文件名,我希望它是下載的確切文件名。例如,如果原來的文件名是struts.pdf,我下載它作爲download.pdf,如何預防和下載的文件與實際文件名Struts 2 Download - 如何動態配置文件名?

我struts.xml的配置如下,

<action name="download" class="action.DownloadAction"> 
     <result name="success" type="stream"> 
      <param name="contentType">application/octet-stream</param> 
      <param name="inputName">fileInputStream</param> 
      <param name="contentDisposition">attachment;filename="download.log"</param> 
      <param name="bufferSize">1024</param> 
     </result> 
     <result name="error">/live/useradminerror.jsp</result> 
    </action> 

我忘了提及使用struts2-jquery開發UI。請幫助我,因爲在我的項目非常關鍵的階段。

回答

11

如果我是正確的,你想通過它被存儲在你的數據庫文件,如果這是你可以很容易地從你的動作類傳遞所有的參數,如

class MyFileDownloadAction extends ActionSupport{ 

    private String fileName; 
    // getter and setter 

    public String fileDownload() throws exception{ 
     // file download logic 
     fileName ="abc" // can set name dynamic from DB 
    } 

} 

<action name="download" class="action.DownloadAction"> 
     <result name="success" type="stream"> 
      <param name="contentType">application/octet-stream</param> 
      <param name="inputName">fileInputStream</param> 
      <param name="contentDisposition">attachment;filename="${filename}"</param> 
      <param name="bufferSize">1024</param> 
     </result> 
     <result name="error">/live/useradminerror.jsp</result> 
    </action> 

你這樣做的情況下,可以在你的struts.xml類中動態地傳遞每個參數。希望這會對你有幫助 這就是你將如何在你的XML中使用這個文件名的方法

+0

感謝您的迴應,它會下載與數據庫中完全相同的名稱。 – Esh 2012-08-01 05:02:37

+1

是的,因爲在這種情況下,您在運行時從您的操作類傳遞文件名 – 2012-08-01 05:06:47

+0

謝謝Umesh,我可以用實際文件名下載文件 – Esh 2012-08-01 06:11:31

1

對於struts中的註釋,它是一樣的。該解決方案非常有幫助。謝謝。 「contentType」對我來說沒有太大的區別。

@Action(value = "/download", results = { @Result(name = "success", type = "stream", 
params= {"contentType", "application/octet-stream", "inputName","fileInputStream",  
"contentDisposition","attachment; filename=\"${fileName}\"", "bufferSize", "1024" }) 
})