QA: Solon 怎么输出下载文件流?

Solon 的Mvc可以直接返回 DownloadedFile 或者 File 对象

@Mapping("/demo/down")
@Controller
public class DownController {
    @Mapping("f1")
    public DownloadedFile down() {
        InputStream stream = new ByteArrayInputStream("{code:1}".getBytes(StandardCharsets.UTF_8));

        //使用 InputStream 实例化
        return new DownloadedFile("text/json", stream, "test.json");
    }

    @Mapping("f2")
    public DownloadedFile down12() {
        byte[] bytes = "test".getBytes(StandardCharsets.UTF_8);

        //使用 byte[] 实例化
        return new DownloadedFile("text/json", bytes, "test.txt");

    }

    @Mapping("f3")
    public File down2() {
        String filePath = Utils.getResource("static/debug.htm").getFile();

        return new File(filePath);
    }
}

还可以通过 Context 对象的 outputAsFile 接口,直接输出下载文件

posted @ 2022-03-07 11:28  带刺的坐椅  阅读(80)  评论(0编辑  收藏  举报