Jsp Example: File Uploading



FileUploading Using JSP(JAVA)

This is an example of the file Uploading in Java using JSP . This file uploading concept Works with the Java as follows

This Java  API parses InputStream of HttpPost request with multipart/form-data encode. By this Java API, only the single method call is enough for your file upload using jsp.In  this example the the file(image) will be saved in your server automatically after you run the application in the Server.

The server takes the default path as the destination if you not specified any path by hard coded.

Using the multipart/form-data you are saying to the server that the request is of type multipart and the data is encrypted data

Intially you have to design the  html file

1)First create the html file by using

–> the file tag in the form attribute(<input type=file name=file1>
–>use the submit tag to send the request to the jsp page.

name these page as the fileupload.html

<form method=”post” action=”/fileUpload.jsp” name=”upform” enctype=”multipart/form-data”>
<table width=”60%” border=”0″ cellspacing=”1″ cellpadding=”1″ align=”center” class=”style1″>
<tr>
<td align=”left”><b>Select a file to upload :</b></td>
</tr>
<tr>
<td align=”left”>
<input type=”file” name=”uploadfile” size=”50″>
</td>
</tr>
<tr>
<td align=”left”>
<input type=”submit” name=”Submit” value=”Upload”>
<input type=”reset” name=”Reset” value=”Cancel”>
</td>
</tr>
</table>
</form>
</body>
</html>

Once the request goes to the jsp the request is collected through getContentType() method (to learn about getContentType)

Then Using the InputSreams and OutputStream the data is modified and do what the way you want the output to show

Name this Jsp file as fileUpload .jsp Your program will run now

<%@ page import=”java.io.*,javax.servlet.http.HttpServletRequest,javax.servlet.ServletInputStream” %>
<%@ page import=”java.io.FileWriter,java.io.IOException,java.io.PrintWriter,java.text.DecimalFormat” %>
<%@ page import=”java.sql.*” %>
<%
String filename = “”;
String contentType = “”, fileData = “”, strLocalFileName = “”;
int startPos = 0, endPos = 0;
%>
<%!
//copy specified number of bytes from main data buffer to temp data buffer

void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)
{
for(int i=start;i<(start+len);i++)
{
toBytes[i - start] = fromBytes[i];
}
}
%>
<%
contentType = request.getContentType();
//out.println(“<br>Content type is :: ” +contentType);
if ((contentType != null) && (contentType.indexOf(“multipart/form-data”) >= 0))
{
DataInputStream in = new DataInputStream(request.getInputStream());
DataInputStream in1 = in;
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength)
{
byteRead = in1.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
//out.println(“<br>totalBytesRead : ” + totalBytesRead + “    :   formDataLength = ” + formDataLength);

//String file = new String(dataBytes);
//out.println(“<br>File Contents:<br>////////////////////////////////////<br>” + file + “<br>////////////////////////////////<br>”);
byte[] line = new byte[128];
if (totalBytesRead < 3)
{
return;    //exit if file length is not sufficiently large
}

String boundary = “”;
String s = “”;
int count = 0;
int pos = 0;

//loop for extracting boundry of file

//could also be extracted from request.getContentType()

do
{
copyByte(dataBytes, line, count ,1);    //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf(“Content-Disposition: form-data; name=\”"); //set the file name
if(pos != -1)
endPos = pos;
}while(pos == -1);
boundary = fileData.substring(startPos, endPos);

//loop for extracting filename

startPos = endPos;
do
{
copyByte(dataBytes, line, count ,1);    //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf(“filename=\”", startPos);  //set the file name
if(pos != -1)
startPos = pos;
}while(pos == -1);
do
{
copyByte(dataBytes, line, count ,1);    //read 1 byte at a time
count+=1;
s = new String(line, 0, 1);
fileData = fileData + s;
pos = fileData.indexOf(“Content-Type: “, startPos);
if(pos != -1)
endPos = pos;
}while(pos == -1);

//to eliminate ” from start & end

filename = fileData.substring(startPos + 10, endPos – 3);

strLocalFileName = filename;
int index = filename.lastIndexOf(“\\”);
if(index != -1)
filename = filename.substring(index + 1);
else
filename = filename;

s = new String(line, 0, 1);
fileData = fileData + s;

//for invoking the value of starting address path

int pic1=fileData.lastIndexOf(“=”)+1;

// for invoking the value of ending address path

int pic2=fileData.lastIndexOf(“C”)-1;
int img1=pic1+1;
int img2=pic2-2;

// for getting the abs path using substring

String filename2=fileData.substring(img1,img2);

// for getting the abs path without quots

filename=fileData.substring(pic1,pic2);

// invoking the file name  without quots

int path=filename2.lastIndexOf(“\\” )+1;
String path1=filename2.substring(path);

// invoing the file extension without quots

int lastpath=filename2.lastIndexOf(“.”)+1;
String lastpath1=filename2.substring(lastpath);
System.out.println(” output “+filename);
out.println(“<img src=”+filename+”></img>”);

FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.write(dataBytes, startPos, (endPos – startPos));
fileOut.flush();
fileOut.close();
}
else
{
out.println(“Error in uploading “);
}

%>

Your image will be saved in path where your server installed

Random Posts

  • Providing current date and time using Stateless session bean
  • What is Thread, How to Use Threads?
  • Life Cycle of Thread
  • What is Finalizer Methods
  • GUI Examples Using Applets

Post a Comment