// csv下载 @RequestMapping(value = "/selectTaskDownFile.do", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<byte[]> selectTaskDownFile(HttpServletRequest req, HttpServletResponse res) { Map<String, Object> map = new HashMap<>(); String path = req.getParameter("path"); try { // ServletContext servletContext = req.getServletContext(); String fileName = path.replaceAll("\\\\", "/").split("/")[path.replaceAll("\\\\", "/").split("/").length - 1]; // String realPath = servletContext.getRealPath(path);// 得到文件所在位置 String realPath = path.replaceAll("\\\\", "/");// 得到文件所在位置 InputStream in = new FileInputStream(new File(realPath));// 将该文件加入到输入流之中 byte[] body = null; body = new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数 in.read(body);// 读入到输入流里面 fileName = new String(fileName.getBytes("gbk"), "iso8859-1");// 防止中文乱码 HttpHeaders headers = new HttpHeaders();// 设置响应头 headers.add("Content-Disposition", "attachment;filename=" + fileName); HttpStatus statusCode = HttpStatus.OK;// 设置响应吗 ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode); return response; } catch (Exception e) { e.printStackTrace(); return null; } }
原文:https://www.cnblogs.com/tanada/p/11386834.html