정적 파일 다운로드

1793 단어 자바
//    
@RequestMapping("downloadDemo")
@ResponseBody
	public synchronized void downloadDemo(HttpServletRequest request, HttpServletResponse response) throws IOException{
		InputStream inputStream = null;
    	ServletOutputStream servletOutputStream = null;
    	try {
    		String filename = "  .xls";
    		String path = "static/file/  .xls";
    		//String path = "static/file/  .xlsx";
    		org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
    		response.setContentType("application/vnd.ms-excel");
    		response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    		response.addHeader("charset", "utf-8");
    		response.addHeader("Pragma", "no-cache");
    		String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
    		response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);        
    		inputStream = resource.getInputStream();
    		response.setHeader("Content-Length", String.valueOf(inputStream.available()));//xlsx         
    		servletOutputStream = response.getOutputStream();
    		IOUtils.copy(inputStream, servletOutputStream);
    		response.flushBuffer();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (servletOutputStream != null) {
						servletOutputStream.close();
						servletOutputStream = null;
					}
					if (inputStream != null) {
						inputStream.close();
						inputStream = null;
					}
					//   jvm      
					System.gc();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

좋은 웹페이지 즐겨찾기