Struts2下载文件

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页面

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值