spring mvc 文件下载
/**前台传过来一个文件名*/ @RequestMapping("/download") public ResponseEntity<Resource> export(@RequestParam("strZipPath") String strZipPath) throws IOException { //filepath 为视频的的路径 //strZipPath 为视频的名字 return download(new File(filepath + "//" + strZipPath)); }
/** * 下载文件 * @param file 文件 */ protected ResponseEntity<Resource> download(File file) { String fileName = file.getName(); return download(file, fileName); } /** * 下载 * @param file 文件 * @param fileName 生成的文件名 * @return {ResponseEntity} */ protected ResponseEntity<Resource> download(File file, String fileName) { Resource resource = new FileSystemResource(file); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); String header = request.getHeader("User-Agent"); // 避免空指针 header = header == null ? "" : header.toUpperCase(); HttpStatus status; if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) { fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8); status = HttpStatus.OK; } else { fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1); status = HttpStatus.CREATED; } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", fileName); return new ResponseEntity<Resource>(resource, headers, status); }
文件下载最好用form表单提交,不要用ajax 提交,因为ajax处理起来很麻烦,如果你想用ajax 可以参考
https://my.oschina.net/watcher/blog/1525962
ps:后台代码都是一样的,就是前台改一下