美文网首页
spring MVC 下载文件

spring MVC 下载文件

作者: Daniel1873 | 来源:发表于2019-01-04 16:29 被阅读0次

    一、传统流方式

    @RequestMapping(value = "antennaAttitudeDownloadFile.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
        @ResponseBody
        public String antennaAttitudeDownloadFile(String path, HttpServletResponse response){
            //判断下载路径是否为空
            if (!StringUtils.isEmpty(path)) {
                //通过绝对路径获取文件
                File file = new File(path);
                //判断文件是否为空
                if (file.exists()) {
                    //生成文件名
                    String fileName = "测听室.txt";
                    // 配置文件下载
                    response.setHeader("content-type", "application/octet-stream");
                    response.setContentType("application/octet-stream");
                    // 下载文件能正常显示中文
                    try {
                        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    // 实现文件下载
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    try {
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        OutputStream os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                            os.flush();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (bis!= null){
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
    
                }
            } 
            return null;
        }
    

    二、通过 ResponseEntity<byte[]> 进行下载

    @RequestMapping(value = "antennaAttitudeDownloadFile.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
        @ResponseBody
        public ResponseEntity<byte[]> antennaAttitudeDownloadFile(String path, HttpServletResponse response) {
            //判断下载路径是否为空
            if (!StringUtils.isEmpty(path)) {
                //通过绝对路径获取文件
                File file = new File(path);
                //判断文件是否为空
                if (file.exists()) {
                    //生成文件名
                    String fileName = "略略略.txt";
                    HttpHeaders headers = null;
                    try {
                        //请求头
                        headers = new HttpHeaders();
                        //解决文件名乱码
                        String downloadFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
                        //让浏览器知道用attachment(下载方式)打开图片
                        headers.setContentDispositionFormData("attachment", downloadFileName);
                        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    try {
                        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    

    写在最后特别注意的是,文件下载发送请求不能以ajax发送异步请求,以ajax发送的请求返回文件会以二进制流回显到response里,如需要以ajax发送需另行配置

    写一种发送请求的方法

    <script>
        $("#btn").click(function(){
            var url = "http://localhost:8081/tiankui-tools-web/antennaAttitude/antennaAttitudeDownloadFile.do";
            var form = $("<form></form>").attr("action", url).attr("method", "post");
            form.append($("<input></input>").attr("type", "hidden").attr("name", "path").attr("value",$("#path").val()));
            form.appendTo('body').submit().remove();
    });
    </script>
    

    相关文章

      网友评论

          本文标题:spring MVC 下载文件

          本文链接:https://www.haomeiwen.com/subject/xuhkrqtx.html