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 请求,否则无反应

猜你喜欢

转载自1960370817.iteye.com/blog/2366205