直接看代码:
下载
文件入口:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="download.action?fileName=<%=java.net.URLEncoder.encode("测试用的RAR.rar","utf-8").toString()
.replace("%","_")%>">测试用的Rar.rar文件</a>
<a href="download.action?fileName=abc.rar">abc.rar</a>
</body>
</html>
下载的action:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import org.apache.struts2.ServletActionContext;
/**
* 实现文件下载的action
* @author acer
*
*/
public class DownLoad {
private String fileName = "";
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getDownloadFile() throws Exception {
fileName = fileName.replace("_", "%");
fileName = URLDecoder.decode(fileName, "utf-8");
System.out.println(fileName);
ServletActionContext.getResponse().setContentType("application/x-msdownload");
FileInputStream fis = new FileInputStream(new File(
ServletActionContext.getRequest().getRealPath("\\upload")+"\\"+fileName));
fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+fileName);
return fis;
}
public String execute(){
return "success";
}
}
配置文件:
<action name="download" class="DownLoad">
<result name="success" type="stream">
<param name="inputName">downloadFile</param>
<param name="bufferSize">1000000</param>
</result>
</action>
这样就可以实现文件的下载了。