将docx文件设置为httpservletresponse

np8igboo  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(360)

我正在尝试设置一个docx文件作为一个api的响应作为附件下载。但是当我下载api生成的文件时,它已经损坏并且无法打开,即使初始文件很好并且可以显示。这是我的控制器方法:

byte[] fileAsBytes= readFileToByteArray(new File(fileLocation))
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=" + "output.docx");
        response.getOutputStream().write(fileAsBytes);

用于获取字节数组的方法

public static byte[] readFileToByteArray(File file){
        FileInputStream fis = null;
        byte[] bArray = new byte[(int) file.length()];
        try{
            fis = new FileInputStream(file);
            fis.read(bArray);
            fis.close();
        }catch(IOException ioExp){
            ioExp.printStackTrace();
        }
        return bArray;
    }

当我尝试打开下载的文件时,它会显示“word发现无法读取的内容”和“word在尝试打开文件时遇到错误”
控制器类中的方法:

@ApiOperation("get file as bytes")
    @PostMapping("/get-file")
    public void getFileAsbytes(HttpServletRequest request,
                                     HttpServletResponse response) throws IOException {

        byte[] fileAsBytes= documentsService.getFileAsBytes();

        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=" + "output.docx");
        response.getOutputStream().write(fileAsBytes);
        response.flushBuffer();
    }

解决:问题是与招摇2版本。此错误在3.0.0版中已修复

yruzcnhs

yruzcnhs1#

问题出在swagger2版本上。此错误在3.0.0版中已修复

相关问题