html页面:

<a href="#" onclick="downLoad()" class="download">下载</a>

我用的ajax像后台发送的请求:

/**文件下载*/
	function downLoad() { 
		  window.open(global_param.context_name+'/upload/fileddown');//此处我用ajax实现调用后台方法。
	}

然后后台具体实现如下:

/**
	 * 文件下载
	 */
	@Transactional
	@Override
	public String fileDown(HttpServletResponse response,HttpServletRequest request) throws Exception {
		String projectPath = request.getServletContext().getRealPath("/");//获取项目的根目录
		String path = projectPath+"/resources/execl/赠送分发.xlsx";//获取到文件exec表的位置,这个地址是你需要下载的文件路径,可以跟你自己的情况写
		File file=new File(path);//创建file对象
		String encoderstr = URLEncoder.encode(file.getName(), "UTF-8");//转字符
		response.setHeader("Content-Disposition", "attachment;filename=\""+encoderstr + "\"");//这样转换后可以避免下载的时候是中文字符
		response.addHeader("Content-Length", "" + file.length()); 
		response.setContentType("application/x-msdownload;"); 
		response.setCharacterEncoding("UTF-8"); 
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());   
		InputStream inputStream = new FileInputStream(file);
		byte[] buffer = new byte[1024];
		int i = -1;
		while ((i = inputStream.read(buffer)) != -1) {
		    outputStream.write(buffer, 0, i);
		}
		outputStream.flush();   
		outputStream.close(); //关闭文件流很关键
		return "success";
	}

 

最后就写完了,希望能帮助到大家!

时间,请带我像一条小溪流般,安静地流淌,汇入爱的海洋。