Detailed explanation of Java Web implementation file upload and download examples
In the development of web applications, the file upload and download function is a very common function. Here is an example of file upload and download realized by Java Web.
For file upload, the browser submits the file to the server in the form of stream during the upload process. It is troublesome to directly use servlet to obtain the input stream of the uploaded file and then parse the request parameters. Therefore, the file upload component of Apache's open source tool common fileUpload is generally selected. The jar package of the common file upload upload component can be downloaded from the Apache official website. Common file upload depends on the common IO package, so you need to download this package.
I File upload
JSP upload page
The following precautions are required for uploading components
Form form: method = "post" enctype = "multipart / form data" belongs to the field: input type = "file" name = "file" size = "50"
These two points are fixed, as shown below
WEB. XML configuration upload path
The upload path can also be written directly in the code, but the configuration is easy to modify here
Process uploaded JSPS
II File download
The download of the file refers to Gushan Canglang's blog, which is written in detail and used directly The basic idea of download is: first traverse all the files in the download directory, and then display them on the page. The client sends a request for download, and the server responds to the download
List all files in the download directory:
Let's briefly talk about the LISTFILE method in listfileservlet. The LISTFILE method is used to list all files in the directory. Recursion is used inside the LISTFILE method. In actual development, we will certainly create a table in the database, which will store the uploaded file name and the specific storage directory of the file, We can know the specific storage directory of the file through the query table. Recursive operation is not required. This example is because the database is not used to store the uploaded file name and the specific storage location of the file, and the storage location of the uploaded file is scattered by hash algorithm. Therefore, recursion is required. During recursion, Store the obtained file name in the map set passed from the outside to the LISTFILE method, so as to ensure that all files are stored in the same map set.
On the web Configure listfileservlet in XML file
Show the LISTFILE. Of the downloaded file The JSP page is as follows:
Realize file download
On the web Configure downloadservlet in XML file
The above is the relevant knowledge of uploading and downloading Java Web files introduced by Xiaobian. I hope it will be helpful to you.