Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
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" %>
<HTml>
<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>
		<br><br><br>
	  <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>
                    <td><INPUT NAME="F1" TYPE="file"></td></tr>
					<tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
             <table>
     </center>      
     </FORM>
</BODY>
</HTML>
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.
getInputStream());
		//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, 
formDataLength);
			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,
contentType.length());
		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))
.getBytes()).length;
		// 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));
		fileOut.flush();
		fileOut.close();
		%><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.

                         

» View all related tutorials
Related Tags: c com jsp file ide files upload types multiple help load output get type ip examples vi tutorial ria this

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

23 comments so far (
post your own) View All Comments Latest 10 Comments:

Hello sir,
Example code works fine for uploading of any kind of data.
Sir, iam requesting you to provide some more detail description about the code to learn how it works.
Thanking you.

Posted by Naidu on Wednesday, 12.17.08 @ 01:21am | #82851

Classic Shit example for this site. Do know how many good programming priniciples you have broken with this one small example?

Posted by a on Tuesday, 12.9.08 @ 08:10am | #82563

Hi,

My problem is that I have to upload a CSV file from Client Machine (Windows) to Unix Application Server.
I am using JSP method post and multipart/form-data (as in described here).
The file is uploaded fine but the problem is it displays carraige Return (^M) a square boxes on Unix file.
I can't ask user to convert file to Unox format before uploading. They just convert excel file to CSV and upload.

Is there any way I can get rid of these characters as I have to use this file further.

Sorry, I can't use any paid utility or tool for it.

I would appreciate if you could please help.

Posted by Ssaurabhw on Tuesday, 12.9.08 @ 07:35am | #82561

Hi,

The code works fine to upload file. But I am uploading csv file from Windows to Unix server. It writes invalid newline charatcter while writing file on Unix server. Can we replace it with valid Unix Format when it's uplloading file.

Thanks,

Posted by sw on Monday, 12.8.08 @ 07:38am | #82511

hoe to run jsp program in details?

Posted by saritha on Friday, 11.14.08 @ 04:10am | #81671

Hi,
I have gone through the code and it is working fine. But if i want the uploaded files are to be stored in a Directory under D Drive what are the changes i need to to in the existing code.Please let me know asap.
Thanks

Posted by naveen on Friday, 11.14.08 @ 02:04am | #81668

How can we upload the files into separate directory unde D drive

Posted by naveen on Friday, 11.14.08 @ 00:02am | #81662

i have tried the file uploading code.i got the output.but the problem is i am unable to get the file name in the mysql database table.Only the filedata and date are displayed.How to get other things into the data base atleast the file name?

Posted by subha on Thursday, 10.30.08 @ 16:37pm | #81415

can we change path at run time? i mean can we take input from client side to store file. or can we store diffrent file in diffrent folder.like take file 'Delhi' store in Delhi's Folder and File 'Gujrat' in Gujrat's Folder

Posted by jitendra on Wednesday, 10.8.08 @ 15:14pm | #80962

Using this code i got :

java.lang.IndexOutOfBoundsExceptiont java.io.FileOutputStream.writeBytes(Native Method) at java.io.FileOutputStream.write(FileOutputStream.java:260)....

I was trying to upload a PDF File. it is something wrong with the code above?

Thanks

Posted by Sserye on Tuesday, 10.7.08 @ 04:40am | #80931

Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.