【发布时间】:2012-02-27 07:37:09
【问题描述】:
需要帮助弄清楚为什么下载的文件大小为 0 字节?单击下载按钮时,页面会弹出一个保存或打开对话框,当我选择保存时,某个位置会保存文件,但它是一个空文件。有什么问题?
JSP 文件
<form target="_blank" method="get" action="/csm/download.action" >
<input type="hidden" id="absFileName" name="absFileName" value="">
<input type="submit" class="btn" id="btnDownloadConfig" value="Download Configuration"/>
</form>
Struts.xml
<action name="download" class="com.abc.csm.actions.DownloadConfiguration">
</action>
我的下载代码
String filePath = ServletActionContext.getServletContext().getRealPath("/")
filePath+=executionResponse
def splits=filePath.split("/")
cfgfileFileName=splits[splits.length-1]
println filePath+", "+cfgfile+", "+cfgfileFileName+", "+executionResponse
File f=new File(filePath)
println("Does file Exists? "+f.exists())
InputStream inputStream = new FileInputStream(f)
response.setContentType("APPLICATION/xml")
response.addHeader("Content-Disposition", "attachment; filename=\""+cfgfileFileName+"\"")
我在控制台中的输出
E:\Tomcat 6\webapps\csm\files//1123/Infa9_1_csmclientbeetle.xml, Infa9_1_csmclientbeetle.xml, files//1123/Infa9_1_csmclientbeetle.xml
Does file Exists? true
我在 tomcat webapps 中的文件位置
E:\Tomcat 6\webapps\csm\files\1123
更新
我找到了一个类似的 question 对我有帮助
这就是我对 InputStream 所做的
FileInputStream ins = new FileInputStream(f)
OutputStream out = response.getOutputStream()
byte[] buf = new byte[1024]
int len = 0
while ((len = ins.read(buf)) >= 0)
{
out.write(buf, 0, len)
}
ins.close()
out.close()
【问题讨论】:
-
你的代码真的做任何与
inputstream相关的事情吗? -
我不知道你为什么要这样做,而使用流结果 (struts.apache.org/2.3.1/docs/stream-result.html) 可以以更干净的方式完成。
-
@Umesh:你有一个例子,我可以在哪里看?谢谢
-
@AbhishekSimon:查看我更新的评论。我相信你没有使用 S2 的真正力量。
-
@Umesh:在那个链接中,它设置了文件名
<param name="contentDisposition">attachment;filename="document.pdf"</param>,但在我的情况下,我需要动态设置它