spring boot中文件下载会把return的内容也写入下载文件

Posted 旁光

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot中文件下载会把return的内容也写入下载文件相关的知识,希望对你有一定的参考价值。

下载部分的代码

前台:

<a  th:href="\'/FileDownload?fileDirType=meeting_minute_docx&fileName=\'+${meetingMsg.meetingId}+\'.docx&fileId=\'+${meetingMsg.meetingId}+\'.docx\'"  >纪要文件.doc</a>

后台:

@ResponseBody
    @RequestMapping("/FileDownload")
    public String  downLoad(HttpServletResponse response,@RequestParam( "fileDirType") String fileDirType,@RequestParam( "fileName") String fileName,@RequestParam( value = "fileId",required = false) String fileId
                           ) throws UnsupportedEncodingException {

        System.out.println("fileDirType:"+fileDirType);
        File fileDir=UploadUtils.getDownLoadDirFile(fileDirType);
        String filePath = fileDir.getAbsolutePath();
        File file = new File(filePath + "/" + fileId);

        System.out.println(file.getAbsolutePath());

        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/plain;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os ; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "下载成功";
        }
        return "下载失败";
    }

下载docx文件打开时有一个问题:(点击是后发现可以正常显示,但发现下载后的docx比原文件大了)

 

 下载txt文件发现多了一个“下”字,也就是说把return中的内容也加进来了。

 

把downLoad方法改为void后下载可正常显示,目前还不清楚原因。

 

以上是关于spring boot中文件下载会把return的内容也写入下载文件的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 返回Html界面

Spring中的观察者模式-事件监听

promise实现return时,会把promise对象return的解决方案

mvc return View() action 参数

idea中applicationContext-dao.xml文件中Cannot resolve file***** :spring xml model validation问题

Spring MVC中常用注解之@SessionAttributes @ModelAttribute详解