Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

JSP File Upload: How to implement File Upload in Java

The concept of file upload is very simple for HTML developers and designers but it is not an easy task for the server-side developers as Java developers. In this article we will talk about the JSP file uploading mechanism step by step.

At the time of file upload process, first we should think about the actual cause for file upload that are usually measured difficult because it is not always clear how the Servlet Application Programming Interface controls them. Basically there are only two ways of primary MIME types for form information: application/x-www-form-urlencoded and multipart/form-data. The first application is MIME type, application/x-www-form-urlencoded, it is the part of MIME type and it is very much true that everybody is accustomed with and the grades in the Servlet Application Programming Interface mechanically or habitually parsing out the name and value pairs. Now information is available by the invoking HttpServletRequest getParameter () or any of the supplementary associated procedures. Now let us discuss the second MIME type, multipart/form-data, which is frequently reflected problematic and very hard to resolve. The only one reason is because the Servlet Application Programming Interface does nothing to help us. Instead the information is left as is and we are answerable for parsing the entire body through either HttpServletRequest getInputStream () or getReader (). We can also use this RFC to determine what way is correct to handhold the information posted to a Servlet. Basically this task is not very problematic or complicated, nevertheless, this is frequently not needed since other developers or designers have created corresponding Application Programming Interface to handle file uploads.

How to Create a File Upload Form

The Java Server Page can be used with a Hypertext Markup Language using the tag to permit the manipulators to upload files to the respective server. The uploaded file type is not always same it may be like text file, image file, video file and also the other format as per our requirement. In this article I will discuss the following steps or protocol (set of rules). This Hypertext Markup Language code is created for an upload form. Following steps are very important for upload process.

  • In the form generally use POST (high security) method instead of GET (low security) method. As it is has very low security process.
  • Encrypt the form attributes that should be set to multipart/form-data process.
  • Action attribute of the form should be conventional to a Java Server Page file that is generally control s the file uploading at the backend server.
  • If we require to upload only one file then we can use a single <input .../> tag with the attribute type="file".
  • Basically it will also allow multiple file uploading, just include more than one input tags with different values for the name attribute.
  • In that types of program model the browser acquaintances a browse button that generally associated with them.
  • Now we will illustrate this system through a program for uploading a file in the web server.

Listing 1:Sample showing uploads form

  <html> 
  <head> 
  <title>Welcome to mrbool Upload process</title> 
  </head> 
  <body> 
  <h3>Now the Uploading respective file…</h3> 
  <p>Select a file to upload</p> 
  <form action="bceiuploadserv" method="post" enctype="multipart/form-data"> 
  <input type="file" name="file1" size="60" /> 
  <br/> 
  <input type="submit" value="Uploading the file……" /> 
  </form> 
  </body> 
  </html>
  

Writing Backend Java Server Page Script

After writing the above code we must start to write the backend server code that is generally used by the following way to let us express the location where the uploaded files would be warehoused. Then we can write unbreakable code in our program or this directory name could also be submitted through an outside arrangement such as a context-param element that is situated in web.xml as showing below.

Listing 2: Sample showing configuration

  <web-app> 
  <context-param> 
  <description>Setup the proper area where the uploaded files will be situated..</description> 
  <param-name>file-upload</param-name> 
  <param-value> c:\apache-tomcat- 7.0.53 \webapps\data\ </param-value><!—Latest version of the apache tomcat server--> 
  </context-param> 
  </web-app>
  

Now in this article I will discuss the original source code of the bceiuploadfile.jsp that is used for handling numerous file uploading in a very fast way.

But when we deliver the code, you should remember the following points.

  1. The above illustration is totally controlled via File Upload, so make sure that the latest version of commons-fileupload.x.x.jar file is present in your classpath. Otherwise it will cause problem at the time of uploading the files.
  2. We may download the requirement files from http://commons.apache.org/fileupload/. Link.
  3. Basically the file upload process is naturally depending on Commons Input Output process, for that reason we make sure that we have the latest version of commons-io-x.x.jar file set in our system class path.
  4. If that particular system is not available in the system then you must use the following link for downloading the file.http://commons.apache.org/io/.
  5. At the time of the testing the following illustration, we can upload the file which has less size than maxFileSize of the server because if the size of the uploaded file is not standard or compatible with the server based system then at lot of problem will arise. So we should remember that the file size must be less than the server capacity.
  6. At time of the uploading file we should be remember that we have created directories c:\temp and c:\apache-tomcat-7.0.53 \webapps\data folder in advance.

Listing 3: Sample showing file upload

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %> 
<%@ page import="javax.servlet.http.*" %> 
<%@ page import="org.apache.commons.fileupload.*" %> 
<%@ page import="org.apache.commons.fileupload.disk.*" %> 
<%@ page import="org.apache.commons.fileupload.servlet.*" %> 
<%@ page import="org.apache.commons.io.output.*" %> 
<% 
File file1; 
int maximumfilesize1 = 3200 * 868; 
int minimumfilesize1 = 3200 * 868; 
ServletContext ctxt = pageContext.getServletContext(); 
String filepath = ctxt.getInitParameter("filedataupload");
// This code is use to authenticate the content type process 
String ctype = request.getContentType(); 
if((contentType.indexOf("multipart/form-data")>=0)) 
{ 
DiskFileItemFactory dfif = new DiskFileItemFactory(); //Initialize the Object 
//set the maximum size that will be stored in system memory. 
factory.setSizeThreshold(maxMemSize); 
// Location to save the data which is larger than maximum and Minimum Size. 
dfif.setRepository(new File("d:\\bcei")); 
// create a new file that use for upload handler 
ServletFileUpload sfu = new ServletFileUpload(dfif); 
// the maximum file size which is to be uploaded here. 
sfu.setSizeMax(maximumfilesize); 
//Exception handling part written here
try{ 
	// this part is written to Parse the request to get file items. 
		List fileitem = upload.parseRequest(request); 
	// this part is written for processing the uploaded file items. 
		Iterator it = fileitem.iterator(); //Initialize iterator  
			out.println("<html>"); 
			out.println("<head>"); 
			out.println("<title>Java Server Page File is used for uploading …</title>"); 
			out.println("</head>"); 
			out.println("<body>"); 
while(it.hasNext()) //set an entry control loop 
{ 
	FileItem fitem = (FileItem)it.next(); 
if(!fitem.isFormField () )//check condition 
{ 
// using following way to get upload file parameters 
	String field_name = fi.getFieldName(); 
	String file_name = fi.getName(); 
	boolean isInMemory = fi.isInMemory(); 
	long sizeInBytes = fi.getSize(); 
// Writing the file in the specific location with proper //path way. 
	if( fileName.lastIndexOf("\\") >= 0 )
	{ 
		file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; 
	}
	else 
	{ 
		file = new File( filePath + 
			fileName.substring(fileName.lastIndexOf("\\")+1)) ; 
	} 
fi.write(file); //write the data inside the file 
out.println("Uploaded Filename:"+filePath+fileName+ "<br>"); 
} 
} 
out.println("</body>"); 
out.println("</html>"); 
}catch(Exception ex) //if any error occurs then system goes to //catch part 
{ 
	System.out.println(ex); 
} 
}
else
{ 
	out.println("<html>");
	out.println("<head>"); 
	out.println("<title>Here the servelet is uploading..</title>"); 
	out.println("</head>"); 
	out.println("<body>"); 
	out.println("<p>System Error : No file Uploaded</p>"); 
	out.println("</body>"); 
	out.println("</html>"); 
} 
%>

 

Simple Image given here that shows us files type, date created, content type and also file id as per our requirement.

Figure 1: Uploading/Downloading file

Process to use a File Upload in Application

From the view of software developers, it is generally very helpful to comprehend the accurate way that is used by the Servlet Application Programming Interface for handling the file uploads process. Basically in most of all real life or practical case we can do away with manually parse and handle a file upload. So the File upload process is nothing new, and several implementations of file upload Application Programming Interface exists. Many open source file upload/download frameworks are also available. The latest release of the framework code (normally JAR file) can be put in the /WEB-INF/lib directory of Web Application. This can greatly simplify our code. Now we consider the FileUpload Servlet.

Listing 4: Sample servlet for file upload

 package com.bcei;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import java.util.*;

public class bceifileuploadcommons  extends HttpServlet 
{
	public void doPost(HttpServletRequest request,HttpServletResponse response)
	throws IOException, ServletException 
	{
		response.setContentType("text/html");
PrintWriter out = response.getWriter(); //out object for the Printwriter class
out.println("<html>");
out.print("File upload success. <a href=\"/jspbook/files/");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
ServletContext sc = getServletContext(); // initialize the sc object for ServletContext
String path = sc.getRealPath("/files");
org.apache.commons.fileupload.FileUpload fu = new org.apache.commons.fileupload.FileUpload();
fu.setSizeMax(-1); //file size initialize  through -1 
fu.setRepositoryPath(path);
//exception handeling process is start from here.
try
{
	List l = fu.parseRequest(request);
	Iterator i = l.iterator();
	while(i.hasNext())
	{
		FileItem fi = (FileItem)i.next();
		fi.write(path+"/"+fi.getName());
	}
}
// If any error will be occur the this message will alert
catch(Exception e)
{
	throw new ServletException(e);
}
out.println("</html>");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException 
{
	doPost(request, response);
}
}

  

The code more thoroughly follows good object-oriented programming by abstracting request parsing reason.

Temporary Directory

As per virtual directory temporary directory is very much important part for the server configuration process. It is helpful feature of the Servlet specification. The actual location of the temporary directory is not stated or specified, nevertheless all the vessels are liable for creating a temporary directory and setting a java.io.File object that is generally denoted through the following directory as the javax.servlet.context.tempdir ServletContext representative.

Basically the Information stored in this directory is only mandatory to persist while the Web Application is running through the system, and the data or the information that stored in the temporary directory will always be hidden from other Web Applications running on the same server for the security purpose.

The container-defined in the temporary directory is helpful for one really important reason: The Web Applications can be run directly from a WAR; but unfortunately there is no guarantee that we can trust ServletContext getRealPath() to always work. Now we are using the javax.servlet.context.tempdir attribute. There are also some few more use cases where the javax.servlet.context.tempdir attribute is required. The temporary directory that provides a place to temporarily store files which is uploaded or any other information of a Web Application. The Web Application which will be deployed outside of the WAR, mostly at that movement we have to control over the deployment; But some cases where the Web Application is anticipated for natural use, we must provide temporary directory that always be used to guarantee concentrated portability of our code or program.

Process of File Upload through Asynchronous JavaScript and xml

Uploading the file without using page refresh is the concept of the Asynchronous JavaScript and xml. Through the AJAX script we can implement procedure of upload file and try to see the preview without refreshing the pages. Because the page refreshing is very slow process if we do the page refresh more than one time. The system will also be slower and an abnormal error will occur. We can also very easily save the uploaded files with a given name into the database by means of a simple prepared statement.

Conclusion

In the server based application model we know that each and every server application needs some type of download and upload process. We know that the internet system is totally developed via protocol system. There are different types of the protocol present like Transmission Control Protocol/ Internet Protocol, Simple mail transfer protocol, Hypertext transfer protocol, File transfer protocol etc. Nevertheless, the point to be remembered is that this upload process also controlled via the File transfer protocol. Here in this article we have given a proper idea about the file uploading and storing in the server application.

This job is not a simple task but it is too much difficult than other processes. When a designer or developer develops the web application using the Java platform then they should think about the two types of technology, one is that Java Server Pages, other is that Servlet. We have already discussed that server application is totally dependent on the server configuration model. If we cannot maintain our server then a lot of disturbance will occur at the time of uploading.

Here we have discussed tomcat apache server. This is the best quality server designed by java language to configuration upload and download. File transfer protocol is dedicated for downloading the file from source server. Also remember that the file server size must be higher than upload file size if any person does not have any clear idea of the actual size of the file then the designer or the software developer must give an alert message. Software developer and the designer as well as network configuration manager must know the latest version of the apache tomcat server; most of the cases we found out that lower version of system creates unnecessary problem.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login