9

I want to write simple rest api for file download.

I cant find docs about it as I understood I need to set mimetype='application/zip' for response, but not clear how to return stream.

http://sparkjava.com/

update: resolved here example code:

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;
zero323
  • 322,348
  • 103
  • 959
  • 935
kain64b
  • 2,258
  • 2
  • 15
  • 27
  • Just a note: error codes `4xx` is a client error, not a server error which usually should be `5xx`. – scrutari Sep 20 '17 at 16:36

1 Answers1

8

What you need is similar to this thread. You only need to close the OutputStream and return the raw HTTPServletResponse:

try {
    ...
    zipOutputStream.flush();
    zipOutputStream.close();
} catch (Exception e) {
    halt(405,"server error");
}
return responce.raw();
Community
  • 1
  • 1
an3m0na
  • 183
  • 2
  • 6