使用struts2的 下载

jsp:

<a href="testDownloadFiles!xiazai.action?fileName=aaa.rar">不带中文名的文件</a><br>
<a href="testDownloadFiles!xiazai.action?fileName=<%=java.net.URLEncoder.encode("宜春院.rar","utf-8").toString().replace("%","_") %>">下载带中文的文件</a>

配置文件struts.xml

<package name="sk-default" extends="struts-default,json-default">
<action name="testDownloadFiles" class="com.TestDownloadFiles">	
			<result name = "input" type="stream">
				<param name="inputName">downloadFile</param>
				<param name="bufferSize">1024</param>
				<param name="contentDisposition">attachment;filename="${fileName}"</param>
			</result>
	</action>
   </package>

java:

	private String fileName;
	
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	//下载
	public String xiazai(){
		System.out.println("执行下载");
		return "input";
	}
	//配置文件中对应的属性<param name="inputName">downloadFile</param>	
	public InputStream getDownloadFile() throws UnsupportedEncodingException, FileNotFoundException{
				fileName = fileName.replace("_","%");
		fileName = java.net.URLDecoder.decode(fileName,"utf-8");
		System.out.println("转码前:"+fileName);
		response.setContentType("application/x-msdownload");
		FileInputStream fileInputStream = new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("")+"\\"+fileName));//文件物理盘位置
		fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");
		System.out.println("下载文件名(转码后):"+fileName);
		//response.setHeader("Content-disposition","attachment;filename="+fileName);
		
		return fileInputStream;
	}

}


你可能感兴趣的:(下载,struts2.0)