• 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:后台代码都是一样的,就是前台改一下

  • 相关阅读:
    Delphi操作Excel大全
    一名Delphi程序员的开发习惯
    七维互联(www.7wei.com)
    Android开发数据库三层应用-DataSnap
    如何破解excel宏的密码
    让Delphi的DataSnap发挥最大效率
    使用 TRegistry 类[1]: 显示各主键下的项
    ini 文件操作记要(1): 使用 TIniFile
    Delphi经验总结(1)
    Delphi经验总结(2)
  • 原文地址:https://www.cnblogs.com/liouzeshuen/p/10605615.html
Copyright © 2020-2023  润新知