springmvc download file from server

@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();
			}
		}
	}
 

 Note: Use the response method to download the file, you cannot use the ajax request, otherwise there is no response

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326262946&siteId=291194637