10

我想为文件下载编写简单的rest api。

我找不到关于它的文档,因为我知道我需要设置mimetype='application/zip'响应,但不清楚如何返回流。

http://sparkjava.com/

更新:在这里解决示例代码:

public static void main(String[] args) {
    //setPort(8080);
    get("/hello", (request, responce) -> getFile(request,responce));
}

private static Object getFile(Request request, Response responce) {
    File file = new File("MYFILE");
    responce.raw().setContentType("application/octet-stream");
    responce.raw().setHeader("Content-Disposition","attachment; filename="+file.getName()+".zip");
    try {

        try(ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(responce.raw().getOutputStream()));
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)))
        {
            ZipEntry zipEntry = new ZipEntry(file.getName());

            zipOutputStream.putNextEntry(zipEntry);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bufferedInputStream.read(buffer)) > 0) {
                zipOutputStream.write(buffer,0,len);
            }
        }
    } catch (Exception e) {
        halt(405,"server error");
    }

    return null;
4

1 回答 1

9

你需要的是类似于这个线程。您只需要关闭 OutputStream 并返回原始 HTTPServletResponse:

try {
    ...
    zipOutputStream.flush();
    zipOutputStream.close();
} catch (Exception e) {
    halt(405,"server error");
}
return responce.raw();
于 2015-03-09T12:04:00.680 回答