File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes What's the best way to download files from a web app? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "What Watch "What New topic

What's the best way to download files from a web app?

Aique Fernandez

Joined: May 04, 2010
Posts: 3

I'm developing a J2EE application and I'm a little stuck.

I use a CMS to store PDF files. I can access to this files from a servlet and obtain his content in a Stream, but I can't access to the path. I want to offer the possibility to download the file.

How can I do that?.

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63868

How can you access the files?

[Asking smart questions] [About Bear] [Books by Bear]
Gokul Nanthakumar
Ranch Hand

Joined: May 11, 2010
Posts: 56
1. set your response content type to application/pdf (MIME type for pdf) (response.setContentType)
2. write the file stream to the response

when browser access your servlet, it will open download dialog box as the content type is not html.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
3. Be sure to set the content-length also, just in case the client needs it.

Mark E Hansen
Ranch Hand

Joined: Apr 01, 2009
Posts: 650
There's an Article in the ServletsFaq:
Note that the same methodology applies to downloading content of various types, including PDF files.
prasenjitkumar das

Joined: Mar 17, 2010
Posts: 12
Try this code snippet :-
(But I am assuming you have a fixed file path)

Manish Singh
Ranch Hand

Joined: Jan 26, 2007
Posts: 160
@prasenjit.svnit das the complete code should not be provided.
The suggestions given by Gokul is enough
I agree. Here's the link:
subject: What's the best way to download files from a web app?
It's not a secret anymore!