zoukankan      html  css  js  c++  java
  • 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:后台代码都是一样的,就是前台改一下

  • 相关阅读:
    Kotlin入门(20)几种常见的对话框
    Kotlin入门(19)Android的基础布局
    Kotlin入门(18)利用单例对象获取时间
    Kotlin入门(17)等式判断的情况
    Kotlin入门(16)容器的遍历方式
    Kotlin入门(15)独门秘笈之特殊类
    Android Studio Gradle被墙bug总结
    unity常用的坐标系转换
    欧拉角与万向节死锁
    Unity导出Gradle工程给Android Studio使用
  • 原文地址:https://www.cnblogs.com/liouzeshuen/p/10605615.html
Copyright © 2011-2022 走看看