1、download.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<a href="download.action?filename=20131021天津投资.doc">下载</a>
2、
Struts.xml:
<action name="download" class="DownloadAction">
<param name="inputPath">/upload/</param>
<result name="success"type="stream">
<!-- 将前台的编码格式转换为ISO8859-1 -->
<param name="contentType">charset=ISO8859-1</param>
<param name="inputName">targetFile</param>
<!--filename是显示给用户看的文件名称-->
<param name="contentDisposition">attachment;filename="${filename}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
3、
import java.io.File;
import java.io.InputStream;
importjava.io.UnsupportedEncodingException;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionSupport;
public class DownloadAction extendsActionSupport {
privateString inputPath;
privateString filename;
publicString getFilename() {
//与struts配置中的<paramname="contentDisposition">attachment;filename="${filename}"</param>相对应
try{
returnnew String(filename.getBytes(), "ISO8859-1");
}catch (UnsupportedEncodingException e) {
//TODO Auto-generated catch block
return "文件下载出现错误";
}
}
publicvoid setFilename(String fileName) {
//将文件名的编码格式有ISO8859-1转换为gb2312,
//ISO8859-1与struts配置的<param name="contentType">charset=ISO8859-1</param>对应
//gb2312与前台的pageEncoding对应
try{
this.filename= new String(fileName.getBytes("ISO8859-1"),"gb2312");
}catch (UnsupportedEncodingException e) {
//TODO Auto-generated catch block
System.out.println("文件名错误");
}
}
publicvoid setInputPath(String value){
inputPath=value;
}
publicInputStream getTargetFile() throws Exception{
ActionContextctx=ActionContext.getContext();
System.out.println("-------------------------------------------------------------filename:"+filename);
Stringfiletest="D:\\tomcat\\apache-tomcat-5.5.30\\webapps\\StrutsDemo\\upload\\"+filename;
System.out.println(filetest);
Filef=new File(filetest);
if(f.exists())
System.out.println("文件找到了");
else
System.out.println("文件没找到");
returnServletActionContext.getServletContext().getResourceAsStream(inputPath+filename);
}
}