方法1、在struts中使用servlet下载
public class DownLoadAction extends ActionSupport {
public String download() throws IOException{
HttpServletResponse response = ServletActionContext.getResponse();
String path = ServletActionContext.getRequest().getRealPath("/Download/旅行.jpg");//获得资源绝对路径
String filename = path.substring(path.lastIndexOf("\\")+1);//获得文件名
filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码
// response.setHeader("content-disposition", "attachment;filename="+filename);//如果资源名称是中文,则应该用URLEncoder转码,设置响应头为文件下载
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
InputStream in = null;
OutputStream out = null;
try{
in = new FileInputStream(path);//读文件
int len = 0;
byte []buf = new byte[1024];
out = response.getOutputStream();
while((len = in.read(buf)) > 0)
{
out.write(buf,0,len);//写入response对象
}
}finally{//关闭流
if(in != null){
try{
in.close();
}catch(Exception e){}
}
if(out != null){
try{
out.close();
}catch(Exception e){}
}
}
return null; //一定要返回null,所以在<action></action>中不用配置result
}
}
2、使用Response下载
DownLoadResponseAction.java
public class DownLoadResponseAction extends ActionSupport {
//filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
private String filename;
@Override
public String execute() throws Exception {
filename = new String(filename.getBytes("iso-8859-1"),"UTF-8");//改编码
System.out.println(filename);
HttpServletRequest request = ServletActionContext.getRequest();//获得request
HttpServletResponse response = ServletActionContext.getResponse();//获得response
String path = request.getRealPath("/DownLoad");//得到资源的路径
File file = new File(path+filename);
response.setCharacterEncoding("UTF-8");
filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码
response.setHeader("content-disposition", "attachment;filename="+filename);//设置响应头为文件下载
response.setContentLength((int)file.length());
int len = 0;
byte []buffer = new byte[1024];
InputStream is = new FileInputStream(file);
OutputStream os= response.getOutputStream();//向浏览器写数据
while((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
is.close();
os.close();
return null;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}