如何使用java spark下载文件?

时间:2014-12-02 08:19:42

标签: java rest spark-java

我想为文件下载编写简单的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;

1 个答案:

答案 0 :(得分:9)

您需要的内容与this thread类似。您只需要关闭OutputStream并返回原始HTTPServletResponse:

try {
    ...
    zipOutputStream.flush();
    zipOutputStream.close();
} catch (Exception e) {
    halt(405,"server error");
}
return responce.raw();