Skip to content Skip to sidebar Skip to footer

Jsp Code for File Upload and Display

17.1 Overview of JSP File Uploading

We have seen several examples in this tutorial where customer sends text data but we can upload text, binary, paradigm or any other type of files on server as well. You must have seen this functionality in several website similar uploading resume on job portal.

HTML provides a different blazon of input chemical element with type "file". Nosotros can use this element in a form like beneath

<input type="file" name="fileName">

All browser displays it slightly different. For example Chrome will display like -

This element volition display "Chose File" button which tin can be used to select the file from client machine that needs to exist uploaded (refer below figure)

On click of "Choose File" push, file selector will be opened with which a file tin can be selected and on selecting the file , chosen file proper name will exist displayed instead "No file chosen"

whereas Internet Explorer displays Scan button similar

Whenever client needs to upload a file , at that place are several important points which needs to exist keep in listen.

· The course method attribute must be set to POST method and Become method cannot be used. Remember with Go, information is sent as a query string so we cannot utilize Go type while uploading files.

· Additional form aspect (enctype) should be set up to multipart/course-information. This attribute informs the server that file is uploaded.

· We need to use ane <input type="file" name="fileName">tag for each file. If we need to upload multiple files uploading, we demand to include more than one input tags with different values for the name aspect. The browser associates a Browse button with each of them.

17.2 Ways to Upload the file

There are two ways to upload a file to server

a) Using third party Jar File – Apache provides a convenient and powerful API to upload the files on server. This arroyo requires below two jar files to be added in WEB-INF/lib directory of web awarding.(You lot candownload these jar files fromhttp://commons.apache.org/fileupload/ )

· commons-fileupload.jar

· eatables-io.jar

b) Servlet 3.0 API - Servlet iii.0Specification provided additional back up for uploading files to server and we donot take to include whatsoever tertiary party APIs.

Let'southward discuss each arroyo in detail

17.two.1 File Upload with Apache Commons File Upload Utility

Apache Commons file upload utility provides DiskFileItemFactory factorycalss that provides a method to parse the HttpServletRequest object and return list of FileItem class( Listing of file item because we can upload multiple file in a one go )

FileItem provides useful method to go the file name, field name in course, size and content type details of the file that needs to be uploaded. To write file to a directory, we can create a File object and laissez passer it as argument to write() method of FileItem course.

Permit'due south write an example to upload file using apache common files upload utility.

Create auploadFile.jsp file – This file volition display an pick to upload the file and will submit the request to processUploadedFile.jsp

<html>   <caput>     <title>File Upload Example using Apache eatables File Upload Utility </title>   </head>   <trunk>     <class activeness="processUploadedFile.jsp" method="post"         enctype="multipart/form-data">         Select File to Upload:<input blazon="file" proper name="fileName"><br>        <input type="submit" value="Upload">     </form>   </body> </html>

Add external jar files in lib directory –Add commons-fileupload.jar and eatables-io.jar file in WEB-INF/lib directory of web application.

Add context param in web.xml – Add together context param in web.xml to configure the path where the file will be uploaded and with which proper noun it will be uplaoded. We can configure the name in several ways (may be holding file etc) but in this case we will configure it equally a context param.

In beneath configuration,

- I have configured 1 param with the name equally fileLocation and value as C\testfolder which means files will be uploaded on c bulldoze

- One parm with proper noun fileName with value sample.txt which ways file uploaded at destination with proper noun sample.txt

<context-param>     <param-proper name>fileLocation</param-name>     <param-value>C:\examination\</param-value> </context-param> <context-param>     <param-name>fileName</param-proper noun>     <param-value>sample.txt</param-value> </context-param>        

Create processUploadedFile.jsp file – Whole logic of uploading a file to server will be in this file. Once uploaded, message will be ready every bit request attribute and asking will be forwarded to response.jsp

<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@page import="org.apache.eatables.fileupload.servlet.ServletFileUpload"%> <html>   <head>     <championship>Process Upload File</championship>   </caput>   <body>     <%@page import="java.io.File"%>     <%@page import="java.util.*,org.apache.commons.fileupload.FileItem"%>     <%       String fileUploadPath = application.getInitParameter("fileLocation");       String fileName=  application.getInitParameter("fileName");       ServletFileUpload uploader= newServletFileUpload(newDiskFileItemFactory());       List<FileItem>fileItemsList = uploader.parseRequest(asking);       Iterator<FileItem>fileItemsIterator = fileItemsList.iterator();       while(fileItemsIterator.hasNext())       {        FileItemfileItem = fileItemsIterator.side by side();        longsizeInBytes= fileItem.getSize();        File file = newFile(fileUploadPath+File.separator+fileName);        fileItem.write(file);        Cord message = fileName + "(" + sizeInBytes + " Bytes) has been uploaded at " + fileUploadPath + "successfully !!" ;        asking.setAttribute("message", bulletin);       }        getServletContext().getRequestDispatcher("/response.jsp").forrard(        request, response);      %>   </body> </html>        

Create response.jsp file – Once the file is uploaded, this jsp will display the message prepare as a request attribute processUploadedFile.jsp

<html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-i">     <championship>File Upload Result</title>   </head>   <body>     <stiff>       <%=        request.getAttribute("message")       %>     </potent>   </trunk> </html>        

Testing

Access uploadFile.jsp using http://localhost:8080/jsp-tutorial/uploadFile.jsp

Click on Browse button to select the file. One time selected, click Upload push button to upload the file . Y'all volition run across below screen.

Verify that sample.txt file on C:\test location

17.ii.ii Servlet 3.0 API

Servlet 3.0 specification provided additional support for uploading files to server and we practice non have to include whatever tertiary political party APIs.

Below are the key things that need to keep in listen

MultiPart note OR configuration in web.xml – We need to add together @MultiPart annotation on the servlet or need to add together in web.xml (in corresponding jsp/ servlet). With this notation nosotros tin configure some information similar maximum size of file that tin be uploaded , location etc

New methods has been added in HttpServletRequest to get all the parts in multipart/form-data request throughgetParts() method. Nosotros can get a specific part using getPart(String partName) method.

Part interface represents a role or form particular that was received inside a multipart/form-information POST asking. We can phone call getInputStream() or write(String fileName) to read and write file.

Lets write an example to come across how we can use Servlet 3.0 API to upload the files.

Add entry in web.xml (Highlighted context params are aforementioned which we added in higher up example)

<context-param>     <param-name>fileLocation</param-name>     <param-value>C:\test\</param-value> </context-param> <context-param>     <param-name>fileName</param-name>     <param-value>sample.txt</param-value> </context-param> <servlet>     <description></description>     <servlet-name>UploadFile</servlet-name>     <jsp-file>/uploadFileWithServlet3API.jsp</jsp-file>     <multipart-config>         <max-file-size>20848820</max-file-size>         <max-request-size>418018841</max-request-size>         <file-size-threshold>1048576</file-size-threshold>     </multipart-config> </servlet> <servlet-mapping>     <servlet-name>UploadFile</servlet-proper noun>     <url-pattern>/uploadFileWithServlet3API.jsp</url-pattern> </servlet-mapping>        

Create uploadFileWithServlet3API.jsp file – Whole logic of uploading a file to server volition be in this file. Once uploaded, message will be set as request attribute and request volition be forwarded to response.jsp

<html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">     <title>File Upload Case using Servlet 3.0 API  </title>   </head>   <trunk>     <grade activity="uploadFileWithServlet3API.jsp" method="post"         enctype="multipart/course-data">         Select File to Upload:<input blazon="file" name="fileName"><br>         <input type="submit" value="Upload">     </form>   </body> </html>        

Create response.jsp file – Once the file is uploaded, this jsp will brandish the bulletin fix as a request attribute uploadFileWithServlet3API.jsp

<html>   <head>     <title>Procedure Upload File</title>   </head>   <trunk>     <%@page import="java.io.File"%>     <%       String fileUploadPath = application.getInitParameter("fileLocation");       String fileName=  application.getInitParameter("fileName");       for (Part part : request.getParts()) {         part.write(fileUploadPath + File.separator + fileName);       }       request.setAttribute("bulletin", fileName + " uploaded at "+ fileUploadPath + " successfully!");       getServletContext().getRequestDispatcher("/response.jsp").forward(       asking, response);     %>   </torso> </html>        

Testing

Access fileUpload.jsp using http://localhost:8080/jsp-tutorial/fileUpload.jsp

Click on Browse button to select the file. Once selected, click Upload button to upload the file. Yous will meet below screen.

Verify that sample.txt file on C:\test location

Note: In real world scenario, alwaysrun a virus scan on the file which is existence uploaded from customer machine because someone may upload the infected file intentionally or un-intentionally.

barnesrect1999.blogspot.com

Source: https://www.wideskills.com/jsp/jsp-file-uploading

Post a Comment for "Jsp Code for File Upload and Display"