1.新建action
private String fileName;
//提供set方法,Struts参数注入
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileName() throws UnsupportedEncodingException {
//处理get传参乱码问题(a标签通过链接传参
return new String(fileName.getBytes("iso-8859-1"),"utf-8");
}
//下载文件的方法、返回到配置文件中处理
public String downloadFile() {
return "downloadFile";
}
//返回文件流的方法
public InputStream getAttrInputStream(){
String path = "uploadDir/";
InputStream attrInputStream = ServletActionContext.getServletContext().getResourceAsStream(path+fileName);
return attrInputStream;
}
//下载显示的中文名,(浏览器显示的文件名)
public String getDownFileName(){
try{
//import java.net.URLEncoder;
fileName = URLEncoder.encode(fileName,"UTF-8");
}catch(Exception e){
throw new RuntimeException();
}
return fileName;
}
2.Struts配置文件
<action name="uploadAction" class="com.cys.action.UploadAction">
<!-- 配置action跳转结果 -->
<result name="uploadSuccess">/uploadSuccess.jsp</result>
<result name="error">/login.jsp</result>
<!-- 验证跳转界面 -->
<result name="input">/login.jsp</result>
<!-- 手动添加拦截器后必须添加默认拦截器 -->
<interceptor-ref name="defaultStack"/>
<!-- 添加一个文件上传拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 设置支持上传的文件格式 -->
<param name="allowedTypes">text/plain,image/jpeg</param>
</interceptor-ref>
<!-- 文件下载配置 -->
<result name="downloadFile" type="stream">
<!-- 允许下载的文件的类型:指定为所有的二进制的文件类型,去tomcat的wen.xml里面搜索 -->
<param name="contentType">application/octet-stream</param>
<!-- 对应的就是Action种的属性,返回流的属性,【其实就是getAttrInputStream()】 -->
<param name="inputName">attrInputStream</param>
<!-- 下载头,包括:浏览器显示的文件名 -->
<param name="contentDisposition">attachment;filename="${downFileName}"</param>
</result>
</action>
3.jsp页面