I want code for uploading and downloading a file in JSP.
Firstly, starting the question with "I want code" doesn't yield much helpful response here. Also see this.
As to your actual question/problem "How to upload and download files using JSP?": to start off, to select a file for upload using JSP you need at least a HTML <input type="file">
element which will display a file browse field. As stated in the HTML forms spec you need to set the request method to POST
and the request encoding to multipart/form-data
in the parent <form>
element.
Because the aforementioned request encoding isn't by default supported by the Servlet API, you won't see anything in the request parameter map. To retrieve the uploaded file and the other request parameters, you need to parse the InputStream
of the HttpServletRequest
yourself. But fortunately there's a commonly used API which can take the precious and tedious work from your hands: Apache Commons FileUpload. At their homepage you can find lot of code examples and important tips&tricks in the User Guide and Frequently Asked Questions sections. Read them carefully. Basically you just need to get the InputStream
from the FileItem
object and write it to any OutputStream
to your taste using the usual Java IO way.
And now downloading the file: create a Servlet
which takes the file identifier as request parameter or pathinfo and uses the usual Java IO way to read the file into an InputStream
and writes it to the OutputStream
of the HttpServletResponse
. You need to set at least the Content-Disposition
request header to attachment
which will show a Save As dialogue. Finally just call this Servlet
in the download link or button.
Good luck and in the future please try to ask the question the smart way. The more effort you put in asking a question, the more you will encourage others to post more code. I've only posted hints instead of "complete code examples" so that you need to work it out yourself.
精彩评论