下载文件

前台jsp页面的javascript代码: 

 function download_file(){

    document.location="<%=basepath%>/lpm/fileDownload-download.action?fileName=小刘.xlsx";
  }

在GlobalName.properties中添加

download_dir=e:/datafile/

action类:

@Namespace("/lpm")
public class FileDownloadAction extends BaseAction {

	//告诉浏览器数据是以下载的形式接收
	private String contentType="application/octet-stream;charset=ISO8859-1";//动态下载,charset=ISO8859-1"中文文件名处理,转换成了ISO8859方式的西欧字符集。 

	//告诉浏览器数据将要下载的文件的文件名
	private String contentDisposition="attachment;filename=";
	//设置服务器读取文件的缓冲区大小
	private String bufferSize="4096";
	
	//前台提交过来需要下载的文件的文件名、路径
	private String fileName;//文件的相对路径,形如:/download/系统说明.doc // 指定要被下载的文件路径 


	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(String bufferSize) {
		this.bufferSize = bufferSize;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		try {
			this.fileName = new String(fileName.getBytes("ISO8859-1"), "GBK");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}

	
	// 通过 ServletContext,也就是application 来读取数据, 下载文件的来源流
	public InputStream getInputStream() throws Exception { 
		String download_dir = GlobalName.getProperty("download_dir")+fileName;
	    //return getHttpSession().getServletContext().getResourceAsStream(fileName); 
		File file = new File(download_dir);
		InputStream is = new FileInputStream(file);
		return is;
	} 

	@Action(value="fileDownload-download", 
			results={@Result(name="success",type="stream",
					params={"contentType","${contentType}","inputName","inputStream","contentDisposition","${contentDisposition}","bufferSize","${bufferSize}"})
			})
	public String download() throws Exception { 
		
		// 下载文件源路径
		String downloadFile = GlobalName.getProperty("download_dir")+fileName; 
		java.io.File file = new java.io.File(downloadFile); 
		if(!file.exists()){
			return null; 
		}
		
		String clientFilename= null;
		//下载到客户端的文件名设置
		try {
			clientFilename =  new String(fileName.getBytes(),"ISO8859-1");//中文文件名的处理(文件名中空格会被下划线代替,迅雷不支持)
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
		this.setContentDisposition(this.getContentDisposition()+clientFilename);//设置输出的文件名, 文件名中含有”\“会被转为下划线
		
		return SUCCESS;
  } 
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值