Sunday, October 29, 2006

File Upload - JSP

[1] Add a form tag in your jsp file as shown below:

<form action="upload.jsp" method="POST" enctype="multipart/form-data"> 

<input type="file" name="theFile"> 

</form>

[2] Add snippet code as below in the jsp file mentioned for the attribute action of form tag above i.e. upload.jsp:

<%

String contentType = request.getContentType();

if ((contentType != null) && (contentType.indexOf ("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < byteread =" in.read(dataBytes," file =" new">

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;
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;

String savePath = request.getRealPath ("documents");
saveFile = savePath + "/" + saveFile;
FileOutputStream fileOut = new FileOutputStream(saveFile);

fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

out.println("File saved as " +saveFile);

}

%>