在控制器方法中返回CompletableFuture <t>

时间:2018-11-27 19:06:50

标签: spring spring-mvc

我有两种方法在@RestController中返回CompletableFuture:

@RestController
public class SampleController {

    @GetMapping("/string")
    public CompletableFuture<String> string() {
        return CompletableFuture.supplyAsync(() -> " test123 ")
                .thenApply(String::trim)
                .thenApply(String::toUpperCase);
    }

    @GetMapping("/file")
    public CompletableFuture<FileSystemResource> fileSystemResource() {
        return CompletableFuture.supplyAsync(() -> new File("file.txt"))
                .thenApply(file -> {
                    try {
                        return zipFile(file);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                })
                .thenApply(FileSystemResource::new);
    }

    private File zipFile(File fileToZip) throws IOException {
        File zippedFile = new File("zipped.zip");
        FileOutputStream fos = new FileOutputStream(zippedFile);

        ZipOutputStream zipOut = new ZipOutputStream(fos);
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
        zipOut.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }
        zipOut.close();
        fis.close();
        fos.close();
        return zippedFile;
    }
}

第一个返回预期的String对象,而第二个返回一些散列文本,例如“PK¸£{Mfile.txtKÊILÊIT(。(ÊÌKW0PKãƒ{TPK {£{Mã{Tfile.txtPK6G“ ..类路径。

为什么我没有收到压缩文件? 我正在使用Spring Boot 1.5.17.RELEASE

与Spring Boot 2.1.0中的项目完全相同的方法。RELEASE版本返回漂亮的zip文件。

处理流不是本讨论的主题。

0 个答案:

没有答案
相关问题