对应文件上传的下载
1、javaweb方法实现:
public String download(){
try {
//获取文件ID
String fileID = elecUser.getFileID();
//使用文件ID,查询用户文件列表,获取路径path
ElecUserFile elecUserFile = this.elecUserService.findUserFileByID(fileID);
String fileURL = elecUserFile.getFileURL();//相对路径
String path = ServletActionContext.getServletContext().getRealPath("")+fileURL;
//获取文件名称
String filename = elecUserFile.getFileName();
//为防止中文乱码,重新编码
filename = new String(filename.getBytes("gbk"), "iso8859-1");
//填写下载文件的头部信息
// response.setContentType("application/vnd.ms-excel");//多种文件类型,不知道具体的类型,不用写,默认是所有类型
//setHeader必须写,第一个参数固定写法(内容的处理形式),处理形式有两种情况:(1)inline(内联)点击直接用浏览器打开;(2)附件,可以指定文件名
response.setHeader("Content-disposition", "attachment;filename="+filename);
//使用路径path,查找到对应的文件,转换成InputStream
InputStream in = new FileInputStream(new File(path));
//从响应对象response中获取输出流OutputStream
OutputStream out = response.getOutputStream();
//读取输入流的数据到输出流中
// IOUtils.copy(in, out);//封装好的方法
//手动读写的方法
for(int b=-1;(b=in.read())!=-1;){
out.write(b);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return NONE;
}2、struts2下载方式实现:
2.1、struts-default.xml中的默认实现
2.2、org.apache.struts2.dispatcher.StreamResult类中默认配置:
2.3、struts.xml文件中的配置
2.4、action中方法实现:
注意:
1)需要将filename放入到request域,可以在struts.xml中通过${#request.filename}获取
2)不需要写OutputStream,但是需要将InputStream于对象关联,可以在struts.xml中通过<param name="inputName">inputStream</param>获取
/**
* struts2方式实现文件下载
* @return
*/
public String download(){
try {
//获取文件ID
String fileID = elecUser.getFileID();
//使用文件ID,查询用户文件列表,获取路径path
ElecUserFile elecUserFile = this.elecUserService.findUserFileByID(fileID);
String fileURL = elecUserFile.getFileURL();//相对路径
String path = ServletActionContext.getServletContext().getRealPath("")+fileURL;
//获取文件名称
String filename = elecUserFile.getFileName();
//为防止中文乱码,重新编码
filename = new String(filename.getBytes("gbk"), "iso8859-1");
request.setAttribute("filename", filename);
//使用路径path,查找到对应的文件,转换成InputStream
InputStream in = new FileInputStream(new File(path));
//与栈顶的InputStream关联
elecUser.setInputStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return "download";
}
本文介绍如何在JavaWeb及Struts2框架中实现文件下载功能,包括使用ServletActionContext获取文件路径、设置HTTP响应头以解决中文文件名乱码问题,并通过InputStream与OutputStream完成文件内容的读取与输出。
2301

被折叠的 条评论
为什么被折叠?



