您的位置:首页 > 编程语言 > Java开发

struts2下载文件

2015-11-12 14:41 375 查看
一、jsp页面

页面要有一个超链接,href里面是下载的方法。

<a href="<%=toDownFile%>&patentId=${vo.id}">文件下载</a>


二、struts配置文件

<action name="toDownFile" class="com.sudytech.plugs.shfy.web.action.PatentInformationAction" method="toDownFile">
<result name="success" type="stream">
<!--设置为文件下载类型-->
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<!--下载文件流 -->
<param name="inputName">inputStream</param>
<!--添加参数,即就是下载的名称 -->
<param name="contentDisposition">attachment;fileName="${downloadFileName}"</param>
<!--缓存 -->
<param name="bufferSize">4096</param>
</result>
</action>





三、后台方法

/**
* 下载文档
* @return
*/
public String toDownFile() {
IFwManager manager=null;
try{
manager=FwMgrFactory.getInstance().openFwManager();
PatentInformation2 p=manager.loadPatentInformation(patentId);
if(p != null){
filePath=p.getFilePath();
}
File file=new File(WebplusEnv.getRealPath(filePath));
if(file.exists()){
fileName=p.getFileName();
}else{
responseString("当前文件不存在");
}
}catch(Exception e){
e.printStackTrace();
}
return SUCCESS;
}

// 下载的流
public InputStream getInputStream() {
try {
InputStream in = ServletActionContext.getServletContext()
.getResourceAsStream(filePath);
return in;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/** 文件名 转换编码 防止中文乱码 */
public String getDownloadFileName() {
String downloadFileName = fileName;
try {
downloadFileName = new String(downloadFileName.getBytes(),
"ISO8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return downloadFileName;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: