Sunday, April 1, 2007

File Upload in JSP

Hi,

I would like to post the Code for uploading a file into server.

Requirement
Store the .csv file which is uploading by user in Server.

Here is the code,

1. Display the File upload option in jsp page


<form name="FileUploader" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td width="25%" colspan="1" align="left">File excel:</td>
<td width="75%" colspan="3" align="left"><input type="file" name="DataFile" size="40"></td>
</tr>
</table>
</form>


As i am new to blog, i am not able to display the jsp code in well formated.

Here is the code for reading the uploaded .csv file in back end.

/* Contents of the file will be stored in a String buffer */
StringBuffer fileContents = new StringBuffer( "" );
/* Using getInputStream of request , we can get the file as ServletInputStream*/
ServletInputStream fileInput = request.getInputStream();

/* Contents of the request input stream stored in the fileContent string buffer */
try{
int fileChar = 0;
while ( fileChar > -1 ){
fileChar = fileInput.read();
fileContents.append( ( char ) fileChar );
}

/* keep in mind that all the information about the request along with file information are stored in the fileContent. So we have to remove the unwanted things. Do Sysout to know the information */

String mimeDelimiter = null, fileName = null, temp = null, fileData = null;
StringTokenizer stringTokenizer = new StringTokenizer( fileContents.toString(), "\n" );

int i = 0;
while ( stringTokenizer.hasMoreTokens() ){
temp = stringTokenizer.nextToken();
++i;

if ( i == 1 && temp.startsWith( "---------" ) ){
mimeDelimiter = temp.substring( 0, temp.length() - 1 );
continue;
}

if ( temp.startsWith( "Content-Disposition: form-data; name=\"DataFile\"; filename=\"" ) ){
java.util.StringTokenizer stf = new java.util.StringTokenizer( temp, "\"" );
temp = stf.nextToken();
temp = stf.nextToken();
temp = stf.nextToken();
fileName = stf.nextToken();
break;
}
}

if ( fileName != null && fileName.trim().length() != 0 ){
String fileExtn = fileName.substring( fileName.lastIndexOf( "." ) + 1 );
if ( "csv".equals( fileExtn ) ){
String contents = fileContents.toString();

temp = mimeDelimiter + "\n" + "Content-Disposition: form-data;name=\"DataFile\";
filename=\"" + fileName + "\"" + "\n";

int iStart = contents.indexOf( temp );
iStart = iStart + temp.length() + 3;
temp = mimeDelimiter;

int iEnd = contents.indexOf( temp, iStart );
fileData = contents.substring( iStart, iEnd );

fileData = fileData.substring( fileData.indexOf( "\n" ) + 3 );
fileData = fileData.substring( 0, fileData.length() - 2 );
fileData = fileData.substring( fileData.indexOf( "\n" ) );
fileData = fileData.substring( fileData.indexOf( "\n" ) + 1 );
fileData = fileData.substring( fileData.indexOf( "\n" ) + 1 );

/* Finally we got the file data. now you can do what you want to do.. */
}
}
} catch ( Exception ioe ){
throw new UserDefinedException("Error in File");
}