开发者

Uploading and downloading a file in JSP [closed]

开发者 https://www.devze.com 2022-12-11 09:02 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly bro开发者_运维百科ad, or rhetorical andcannot be reasonably answered in its current form.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly bro开发者_运维百科ad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消