Struts2 下载

action写法
private String fileName;
	private String fileRealName;

	public void setFileName() {
		// 得到请求下载的文件名
		String fname = ServletActionContext.getRequest().getParameter("name");
		String frealname = ServletActionContext.getRequest().getParameter(
				"realname");
		try {
			//转码
			fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
			frealname = new String(frealname.getBytes("ISO-8859-1"), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("模板名称解析错误:"+frealname+e.getMessage());
		}
		this.fileName = fname;
		this.fileRealName = frealname;
	}

	/*
	 * 
	 * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对fileName再次编码
	 * 否则中文名文件将出现乱码,或无法下载的情况
         *此处配置 下载时文件名称
         */
public String getFileName() {
		

	try {
		fileName = new String(fileName.getBytes(), "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		
		return fileName;
		
	}

	/*
	 * @getDownloadFile 此方法对应的是struts.xml文件中的: downloadFile 返回下载文件的流,可以参看struts2的源码
	 */
	public InputStream getDownloadFile() {

		this.setFileName();
		// return
		// ServletActionContext.getServletContext().getResourceAsStream(this.getFileName());
		File fileDes = new File(this.fileRealName);// path是要下载文件所在的路径,可以写成任意本地路径
		InputStream is = null;
		try {
			is = new FileInputStream(fileDes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return is;

	}

	public InputStream getDownloadFileTem() {
		this.setFileName();
                //ServletActionContext.getRequest().getRealPath("/"); 获取项目根路径
                // File.separator;获取系统分割符
		String targetDirectory = ServletActionContext.getRequest().getRealPath("/")
				+ "recording"+ File.separator;
		logger.info("模板路径:"+targetDirectory+this.fileRealName);
		File fileDes = new File(targetDirectory+this.fileRealName);// path是要下载文件所在的路径,可以写成任意本地路径
		InputStream is = null;
		try {
			is = new FileInputStream(fileDes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return is;
	}

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
}
struts 配置
<!-- 文件下载 -->
		<action name="download" class="com.skyon.atmis.action.fileupdown.DownloadAction">
			<result name="success" type="stream">
				<param name="contentType">application/x-msdownload;charset=ISO8859-1</param>  
				<param name="contentDisposition">attachment;filename="${fileName}"</param>
				<param name="inputName">downloadFile</param>
			</result>
		</action>





                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值