Home Jsp File_upload Uploading Single File by Using JSP


Share on Google+Share on Google+

Uploading Single File by Using JSP

This tutorial will help you to understand how you can upload a file by using the Jsp. As Jsp is mainly used for the presentation logic, we should avoid to write a code in the jsp page, but at least we should know how we can use a java code inside the jsp

Uploading Single File by Using JSP


This tutorial will help you to understand how you can upload a file by using the Jsp. As Jsp is mainly used for the presentation logic, we should avoid to write a code in the jsp page, but at least we should know how we can use a java code inside the jsp page. In Jsp the logic of the program or Java code is mainly written inside the scriptlet. In this example we are going to tell you how can make use of scriptlet to upload a file.

In this example we are going to tell you how we can upload a single file by using Jsp and how it will get stored on a particular memory area. To get the desired result firstly we need to need to make a jsp page which will work as a controller, and to fulfill our requirements we need to import some packages, classes and interfaces. For this program we are using one package java.io.* which provides us classes and interfaces for java input/output. 

The logic of the program will be written inside the scriptlet. The scriptlet tag is mostly used for writing the java code inside the jsp. 

In the scriptlet we have used the method getContentType( ) of the implicit object request. This method is used to get the content type information from the Jsp header. The next step we are going to do is to check the condition whether the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0. If the condition is true make a object of DataInputStream. Inside the constructor of the DataInputStream pass the getInputStream() method of the implicit object request reference of the class InputStream. It will create a DataInputStream that uses the specified underlying InputStream. A data input stream read primitive Java data types from an underlying input stream. 

Now we need to get the length of the content type which will be passed as a parameter to the constructor of the byte array. Now declare two int variables and initialize their values as 0. To convert the uploaded file into the byte code use the while loop.  Now pass the array of dataBytes in the constructor of String class and store it in the variable file. To save the file name we need to substring the file object. After making the substring of the string we need to extract the index of file. Upto now we have got the file name and the index of file, now what we need is create an new file with the same name and writing the content in new file. For this we will make a object of class File and pass a new directory name which we want to make as a parameter in the constructor of the File class. By using the File object method mkdir() we will make a directory. To write the content in new file make a object of class FileOutputStream. 

We need another jsp page which will be used for the presentation. This jsp page contains the information where the request will be sent whenever it will get a request for file uploading. To upload the file to the jsp page firstly we need to browse the files and get the appropriate file. This will be achieved by the input type "file". To save the file to the particular location we need a submit button. 

In this program firstly you will get a jsp page which will have the option of browse and Send File. The logic behind it will be controlled by the controller.   

Here is the code of the index_single_upload.jsp: 

<%@ page language="java" %>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>  
<% //  for uploading the file we used Encrypt type of multipart/
form-data and input of file type to browse and submit the file %>
  <BODY> <FORM  ENCTYPE="multipart/form-data" ACTION=
"sinle_upload_page.jsp" METHOD=POST>
	  <center><table border="2" >
                    <tr><center><td colspan="2"><p align=
"center"><B>PROGRAM FOR UPLOADING THE FILE</B><center></td></tr>
                    <tr><td><b>Choose the file To Upload:</b>
                    <td><INPUT NAME="F1" TYPE="file"></td></tr>
					<tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>

Output for the index_single_upload.jsp

Output After Clicking Browse Button:

Here is the code of the single_upload_page.jsp: 

<%@ page import="java.io.*" %>
	//to get the content type information from JSP Request Header
	String contentType = request.getContentType();
	//here we are checking the content type is not equal to Null and
 as well as the passed data from mulitpart/form-data is greater than or
 equal to 0
	if ((contentType != null) && (contentType.indexOf("multipart/
form-data") >= 0)) {
 		DataInputStream in = new DataInputStream(request.
		//we are taking the length of Content type data
		int formDataLength = request.getContentLength();
		byte dataBytes[] = new byte[formDataLength];
		int byteRead = 0;
		int totalBytesRead = 0;
		//this loop converting the uploaded file into byte code
		while (totalBytesRead < formDataLength) {
			byteRead = in.read(dataBytes, totalBytesRead, 
			totalBytesRead += byteRead;
					String file = new String(dataBytes);
		//for saving the file name
		String saveFile = file.substring(file.indexOf("filename=\
"") + 10);
		saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
		saveFile = saveFile.substring(saveFile.lastIndexOf("\\")
 + 1,saveFile.indexOf("\""));
		int lastIndex = contentType.lastIndexOf("=");
		String boundary = contentType.substring(lastIndex + 1,
		int pos;
		//extracting the index of file 
		pos = file.indexOf("filename=\"");
		pos = file.indexOf("\n", pos) + 1;
		pos = file.indexOf("\n", pos) + 1;
		pos = file.indexOf("\n", pos) + 1;
		int boundaryLocation = file.indexOf(boundary, pos) - 4;
		int startPos = ((file.substring(0, pos)).getBytes()).length;
		int endPos = ((file.substring(0, boundaryLocation))
		// creating a new file with the same name and writing the 
content in new file
		FileOutputStream fileOut = new FileOutputStream(saveFile);
		fileOut.write(dataBytes, startPos, (endPos - startPos));
				%><Br><table border="2"><tr><td><b>You have successfully
 upload the file by the name of:</b>
		<% out.println(saveFile); %></td></tr></table> <%

Output for Sinle_upload_page.jsp

Download all files.


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 25, 2008

Related Tutorials

Ask Questions?    Discuss: Uploading Single File by Using JSP   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 2, 2011

Thanks to this beautiful and efficient tutorial makers!!!!!!!!! Thanks for your huge contribution to the programmers struggling with code and new technology...... well,this code will not work for any other file than .txt.....but u can always upload the file into a folder and then copy the url to the database.....that will surely ensure all types of file upload !
April 15, 2011
Fix for Linux Server

For some reason in Linux is raising this exception: java.lang.IndexOutOfBoundsException this only happends with binary files on Linux. To fix, add before this line: int endPos = ((file.substring(0, boundaryLocation)) .getBytes()).length; This lines: if(endPos > formDataLength){ endPos = boundaryLocation; } Warning not fully tested!
April 20, 2011
Upload File at specified location

I want to store a file at specified location Folder what I do for tht....Please.....ans....
June 2, 2011
file uploding

excellent work.
June 15, 2011
After uploading file, where it gets stored?

After uploading the file, if we want to see the uploaded file, where can we get the file?
Utsav Kesharwani
June 14, 2011
File Upload query

Hi, I have followed the code. I am using netbeans as my JSP editor and is using glassfish server. I wanted to know the location of the folder which stores the files when a user uploads them through this JSP page. Thanks.
May 29, 2013

If you are not finding the location of uploaded file, then just do the following: FileOutputStream fileOut = new FileOutputStream("C:\\"+saveFile); so that the file will be uploaded to your C drive. :)
Dhamodharan Ravishankar
September 23, 2011

Find it useful
September 26, 2011

not working.. error in line FileOutputStream fileOut = new FileOutputStream(saveFile);
October 8, 2011
about single image upload

it and fantastic code in jsp.......
February 17, 2013
String index out of range -1

heh, i am Tarun i am following code that u have publish in site ..as that i am getting exception that"string out of range -1" i am resolved this.. please can u suggest me idea to get out of this
November 16, 2011

Hai i had a doubt, uploading a file (.txt, .doc , .html) and images to servers ,both are same ?
Prithwiraj Bose
November 24, 2011
Doesn't Work on Websphere

Hi, I've repeatedly tested the code in Websphere server. But it doesn't work on Websphere. Although it works perfectly in Tomcat.
Ankit Sharma
December 1, 2011

it is really helpfull
December 15, 2011

good job you did here pall...i was searching for this for 2 hours, i thought i have to read the file directly from client machine..but i was wrong...one question though: does this file remain on the server? or is just a temporary one?
January 4, 2012
Knowing file location after execution ?

when i execute my project i don't know the file location after sending
January 5, 2012
Special Characters

Hi! I´m trying to upload files with ñ and acutes but I could not do. I tested with <%@ page language="java" contentType="text/html; charset=ISO-8859-15" pageEncoding="ISO-8859-15"%> I'm trying with this method <% Characters convertion public String convert(String in) { return in.replaceAll("&","&amp;") .replaceAll("ñ","&#241;") .replaceAll("Ñ","&#241;") .replaceAll("ó","&#243;"); } %> but nothing... :( I guess that is the configuration of Apache server
January 6, 2012
thanks for the superb post

It was very much helpful to me and also its very easy concept to upload the files. thanks for the superb post.....
January 12, 2012
can understand

were is the location of the file uploaded
dedi satriya
January 15, 2012
change location upload

how to change the location of image when upload to specified folder
January 16, 2013

how to find the uploaded file from the above source code.
January 13, 2013
query on upload

IS it always that for upload in the jsp the form tag required and can it be done without using the form tag ..? if so den how to set the ENCTYPE="multipart/form-data".
January 18, 2013
How to get value from another test box

This Jsp works fine. But in the html form if I have another input type eq text, how will I capture the value of that text box and append it to the name of the file when I upload the file.
pradip garala
February 2, 2012
nice work

nice work.
February 27, 2012

Files do get uploaded but they are corrupt..please upload the proper code!!!
March 2, 2012
aise hi

March 13, 2012
Single upload code doubt

where does the file get uploaded?im askin the location?
March 23, 2012
Where would it store file

code is fine it works also but where would be the file stored...i need to store the file in a folder and as well in the database plz tell how can we do that
pooja sethiya
March 27, 2012

wher did the file is being saved after uploading???
March 28, 2012
single file upload in jsp

how can i change the saving path of new uploaded file?
March 30, 2012
jsp program

i was try this program but can't save this file error
March 30, 2012
Not able to get other data from the form

I am not able to retrieve a text box value from "index_single_upload.jsp" to "single_upload_page.jsp" using request.getParameter("txt"). Its returning null. Can any body help on this.
April 6, 2012
Where the file will upload

Where can i find the uploaded file.
May 3, 2012
Good Mini-Tutorial

This was helpulf for me... Thanks
July 1, 2012
Uploading file check

This code works fine.I have a problem like a single file can be uploaded any number of time.What should i do to place a check to avoid uploading the same file.Thanks in advance.
July 1, 2012
Uploading file

This code works fine.My problem is ,how to place a check on the file being uploaded to avoid multiple uploading of same file.Thanks in advance
July 25, 2012
The place of saving files??

Hi, Thanks for this tutorial but I'm wondering, after the upload of the file, where it will be saved??? I want to save it in a folder on a remote server thanks and good luck Kim
August 27, 2012
how to get it back

hi, how to retrieve the uploaded documents?
October 19, 2012
It wasnt usefuly at all

Dint work for me
November 7, 2012

can u please explain how to rename this file before saving on the server ??
November 30, 2012
Possible problems becvause of binary files

When the file is binary and you convert the byte array into a String, because of decoding problems, you may get a string with a length possible larger than that of the byte array. Then, the endPos may turn out to be much larger than it should. What I would do is: -Decode using "UTF-8" That alone will not solve all problems, but header will be OK -Since decoding problems can occur in the file contents but are unlikely beyond it, when calculating endPos, look for the distance from the end, rather than from the beginning, that is: int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; int fin = file.getBytes().length; int distfinal = fin - endPos; endPos = dataBytes.length - distfinal;
April 6, 2013
Where to find uploaded file

After file is successfully uploaded ,how to find loaction of file ??
November 27, 2013

The above source is self explanatry and just cool. Gave the path to store the file. And it worked smoothly.
February 1, 2014
upload file

where does the file get stored in the upload code shown in http://www.roseindia.net/jsp/file_upload/Sinle_upload.xhtml.shtml
Sakti Pada Sahoo
August 24, 2011
location of the file uploaded

Hi, I have followed the code. I am using netbeans as my JSP editor and is using glassfish server. I wanted to know the location of the folder which stores the files when a user uploads them through this JSP page.please give me the required suggestions. Thanks.
satriya dedi
January 18, 2012
why if the not select or null the sintak error

why if the not select or null the sintak error