下载文件

前台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;
  } 
}


 

你可能感兴趣的:(下载文件)