Saturday, January 24, 2009

JSP : Simple File Uploading Codes.

We will see how to upload a file using JSP, you can upload a file to your desire location with desire name. Please see the simple self explanatory codes below.

Please add below mentioned jar files in your applications classpath.





1st HTML interface (can be used in JSP as well)

FileUploadingInterface.HTML


<HTML>
<HEAD>
<TITLE>File Uploading Interface</TITLE>
</HEAD>
<BODY>
<center>
<h3>Simple File Uploading Example</h3>
<form action="ProcessUploadedFile.jsp" method="post" enctype="multipart/form-data">
Name <input type="text" name="userName"> (optional) </br></br>
File <input type="file" name="file1"> </br></br> <!-- Here You Can Add more numbers of Files For Uploading -->
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>



2nd JSP code


ProcessUploadedFile.jsp


<%@ page import="java.io.*" %>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.printStackTrace();
}

Iterator itr = items.iterator();

while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();

//Get Other Form Fileds Values in this Block
if (item.isFormField())
{
String itemName = item.getFieldName();
String itemValue = item.getString();
String name = "";
if (itemName.equals("userName"))
name = item.getString();

out.println("User Name "+name);
}
//Get File type Values Here, it could be one or multiple File
else
{
try
{
String itemName = item.getName();

//userFieldName is what u provided in html file
String userFieldName = item.getFieldName();

if(itemName != null)
{
if(itemName.equals(""))
{
//If Nothing Uploaded
out.println("No File Uploaded");
}
else
{
//Provide Destination Folder, Where Uploaded File to be saved
boolean folderMade = (new File("d:/UploadedFileFolder")).mkdirs();

// This is required to filter out file name from complete file path.
int idx = itemName.lastIndexOf("\\");

String filename = "";

if(idx > -1)
{
//in case of IE, it sends complete path. Hence only file name must be filtered out.
idx=idx+1;
filename = itemName.substring(idx);
}
else
{
//in case of other borwsers, its just filename
filename = itemName;
}

File savedFile = new File("d:/UploadedFileFolder/"+filename);
item.write(savedFile);

//Get path of the saved file
String path = savedFile.getPath();

out.println("File Uploaded Sucessfully "+path);

}
}
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//else
}//while
}//else
%>

No comments:

Post a Comment