`

springmvc 从服务器下载文件

 
阅读更多
@RequestMapping(value="exportExcel")
	public void exportExcle(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		File filePath = new File(realPath + "/tempExclePath");
	    String path = filePath+"/"+key+".xlsx";
		final File file = new File(path);
                fileName = file.getName();
		InputStream inputStream;
		try {
	        inputStream = new BufferedInputStream(new FileInputStream(file));
	        byte[] buffer = new byte[inputStream.available()];
	        inputStream.read(buffer);
	        inputStream.close();
	        response.reset();
	        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
	        response.addHeader("Content-Length", "" + file.length());
	        OutputStream os = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	        os.write(buffer);
	        os.flush();
	        os.close();
		} catch(Exception e){
			e.printStackTrace();
		}finally{
			if(file.exists()){ // after download, delete the file on server
				(new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							Thread.sleep(10000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						} finally {
							try {
								file.delete();
							} catch (Exception e) {

							}
						}
					}
				})).start();
			}
		}
	}
 

 注意:使用response 方式下载文件,不能使用ajax 请求,否则无反应,如果用到ajax,可以使用表单的方式,如下:

 

function downlaodFile (params){
var temp = document.createElement("form");
		temp.action = "xxx.do"
		temp.method = "post";
		temp.style.display = "none";
		Object.keys(params).forEach(function(key){
			var opt = document.createElement("input");
			opt.name = key;
			opt.value = params[key];
			temp.appendChild(opt);
			//temp.append(opt);
		});
		document.body.appendChild(temp);
		//document.body.append(temp);
		temp.submit();
		return temp;
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics