springMVC 下载文件

@RequestMapping(value = "/path", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public void download(HttpServletRequest request,HttpServletResponse response) throws IOException {

		String fileName = "";
           byte[] fileBytes = null;
			response.setContentType("application/force-download");
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition","attachment; fileName=" +fileName);
			response.setHeader("Content-Length", String.valueOf(fileBytes.length));
			try {
				
				//获取输入流
				BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(fileBytes));
				//输出流
				BufferedOutputStream  bos = new BufferedOutputStream(response.getOutputStream());
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
				bos.flush();
				//关闭流
				bis.close();
				bos.close();

			}catch (Exception e) {
				LOG.error("文件读取异常",e);
				
			}
		
	}

猜你喜欢

转载自mutourenoo.iteye.com/blog/2408309