使Apache Poi Word文件可通过URL下载

时间:2019-04-10 13:04:41

标签: java ms-word apache-poi

  

poi代码的结尾:

response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("დოკუმენტი-" + loan.getLoanId() + ".zip", "UTF-8"));

File f = new File("autoloanagreement.docx");
FileOutputStream fileOutputStream = new FileOutputStream(f);

document.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Success");

我已在produces = "application/zip"上设置了控制器处理程序方法 每当我下载文件并尝试打开它时,我都会得到

  

档案的格式未知或已损坏

     
    

编辑:

  

我添加了新的代码行,现在下载并打开了zip文件,但收到了新的错误消息“ zip文件意外结束”

ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream(), Charset.forName("UTF-8"));

        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

        DocumentSettingsPart dsp = wordMLPackage.getMainDocumentPart().getDocumentSettingsPart();
        org.docx4j.wml.CTSettings settings = Context.getWmlObjectFactory().createCTSettings();
        BooleanDefaultTrue val = new BooleanDefaultTrue();
        val.setVal(true);

        // Layout Settings
        org.docx4j.wml.CTCompat compat = Context.getWmlObjectFactory().createCTCompat();
        compat.setDoNotExpandShiftReturn(val);
        settings.setCompat(compat);
        dsp.setJaxbElement(settings);
        wordMLPackage.getMainDocumentPart().addTargetPart(dsp);

        File f = new File("AutoLoanAgreement");
        zipOutputStream.putNextEntry(new ZipEntry(f.getName()));
        wordMLPackage.save(f);
        FileInputStream fileInputStream = new FileInputStream(f);
        IOUtils.copy(fileInputStream, zipOutputStream);


        // დავხუროთ სტრიმი
        fileInputStream.close();
        zipOutputStream.closeEntry();

1 个答案:

答案 0 :(得分:1)

您以zip格式发送文件,但似乎从未压缩过要发送的文件。您可以将FileOutputStream包装在ZipOutputStream中,例如

OutputStream out = new ZipOutputStream(new FileOutputStream(f));

而且,您似乎从未真正将文件传递给响应的OutputStream。

尝试:

OutputStream os = new ZipOutputStream(response.getOutputStream());
document.write(os);