目前做的一个项目需要支持迅雷下载,因此在做开发时,发现一个非常奇怪的问题,就是:有时通过迅雷能够下载(文件名称正确),有时不能下载(文件名显示的是*.action,而且无法下载)。希望大神可以帮我看看,具体可以看附件中的图。
下面贴上代码:
----------------------------------------------------
struts.xml :
<action name="download" class="fileLoadAction"
method="fileDownload">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="bufferSize">4096</param>
</result>
</action>
---------------------------------------------------------------
action:
public String fileDownload() throws Exception{
return SUCCESS;
}
public InputStream getInputStream(){
InputStream is = null;
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.reset();
Attachment att = (Attachment) dao.get(Attachment.class, id);//从数据库中读取文件
String fileName = att.getNameSource() + att.getFileType();//获取文件名称
fileName = new String(fileName.getBytes(), "iso8859-1");
response.setHeader("content-disposition", "attachment;filename=" + fileName);
is = att.getFileContent().getBinaryStream();//文件内容转换成流
} catch ( Exception e) {
e.printStackTrace();
}
return is;
}
--------------------------------------------------------------
前台:
<a style="" href="<%=request.getContextPath()%>/fileload/download.ac?id=${obj.idAttachment}"
target="_blank" title="${obj.nameSource}">
--------------------------------------------------------------------
解决方法:
问题找到,原来是这一行代码的问题: fileName = new String(fileName.getBytes(), "iso8859-1");
改成 fileName=URLEncoder.encode(fileName, "UTF-8");就行了,刚刚看别人帖子的注释才知道的(http://blog.youkuaiyun.com/menglingjun/article/details/5356105)