Struts2实现文件下载功能代码分享(文件名中文转码)
struts2文件下载功能实现代码如下所示:
Action文件
public class DownLoadAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 5879762231742395104L;
private String fileName;//用户请求的文件名
private String inputPath;//下载资源的路径(在struts配置文件中设置)
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getInputPath() {
return inputPath;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public String downloadFile() throws Exception {
ServletContext context = ServletActionContext.getServletContext();
String downloadDir = context.getRealPath("/upload");
String downloadFile = context.getRealPath(inputPath);
//防止用户请求不安全的资源
if(!downloadFile.startsWith(downloadDir)) {
return null;
}
return "download_success";
}
/*
* 获取输入流资源
*/
public InputStream getInputStream() throws Exception {
String path = inputPath + File.separatorChar + new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
return ServletActionContext.getServletContext().getResourceAsStream(path);
}
/*
* 获取下载时文件默认的文件名
*/
public String getDownloadFileName() {
String downloadFileName = fileName;
try {
downloadFileName = URLEncoder.encode(downloadFileName, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.getMessage();
e.printStackTrace();
}
return downloadFileName;
}
}
jsp文件:
struts.xml:
/upload
application/octet-stream
inputStream
attachment;filename="${downloadFileName}"
2048
以上所述是小编给大家介绍的Struts2实现文件下载功能代码分享(文件名中文转码)的相关内容,希望对大家有所帮助!相关阅读:
这才是正式版?Win10 RTM升级Win10 10240 TH1八月更新版的详细教程
浅析is_writable的php实现
简单谈谈PHP中的include、include_once、require以及require_once语句
怎么用百度升级Windows 10正式版? 搜索即得
自定义 DataList 显示数据行数的方法
php中使用$_REQUEST需要注意的一个问题
C#使用Parallel类进行多线程编程实例
jquery ajax,ashx,json的用法总结
php不写闭合标签的好处
JavaScript Serializer序列化时间处理示例
C#中单例的实现方法
举例讲解Java设计模式编程中模板方法模式的运用实例
javascript数组快速打乱重排的方法
Android中自定义ContentProvider实例