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后下载可正常显示,目前还不清楚原因。

 

posted @ 2020-03-15 11:06  旁光  阅读(999)  评论(0编辑  收藏  举报