In Play 2.6 to download a file I set the following headers:
response().setContentType("application/x-download");
response().setHeader("Content-disposition","attachment; filename=" + f.getFilename());
return ok(new java.io.File("public/tmp/" + f.getFilename()));
Now I’m trying to do same thing with 2.7.
java.io.File file2download = new java.io.File("public/tmp/" + file.getFilename());
java.nio.file.Path path = file2download.toPath();
Source<ByteString, ?> source = FileIO.fromPath(path);
Optional<Long> contentLength = Optional.of(file2download.length());
return new Result(
new ResponseHeader(200, Collections.emptyMap()),
new HttpEntity.Streamed(source, contentLength, Optional.of("application/x-download"))
);
How can I add the filename to the Stream?
mkurz
(Matthias Kurz)
2
You don’t need to code all that by yourself, Play extracts the filename, content-length etc. for you already. All you need to do is:
return ok(file, false);
The second param tells Play to not use inline
content disposition but attachment
.
1 Like
Thanks, it’s work. But if I would to use the other method to download big data using HttpEntity.Streamed, is it possible to set the filename?
mkurz
(Matthias Kurz)
4
Please read https://www.playframework.com/documentation/2.7.x/JavaStream#Serving-files
If you use
return ok(file, false);
Play will already add the filename to the header for you and will also use HttpEntity.Streamed
to send the file. You don’t need to do more.
However if you want to use a different filename you can use:
return status(OK).sendFile(file, false, "myfile.pdf");
this again does the same what your code tries to achieve.
BTW: Upcoming Play 2.7.1 will provide even more helper methods, meaning you will then be able to just write:
return ok(file, false, "myfile.pdf");
Hope that helps!
1 Like