Professional Documents
Culture Documents
How To Upload Files Using JavaServer Pages
How To Upload Files Using JavaServer Pages
How To Upload Files Using JavaServer Pages
Uploading files to a web server in JavaServer pages proves to be sometimes technical. This is why I
came up with these simple JavaServer pages in order to achieve this. There is a Windows and a Linux
version, though the procedures involved are more or less the same. The Windows version was tested on
a Microsoft Windows 2000 Professional system whereas the Linux companion was done on Red Hat 9.0.
The web server of service was Apache Tomcat 5.5 in both cases.
<html>
<head>
<title>File Upload in JSP</title>
</head>
<body>
<FORM ACTION="upload.jsp" ENCTYPE="multipart/form-data" METHOD=POST>
Which file do you want to upload? <INPUT TYPE=FILE NAME=file> <BR>
<INPUT TYPE=SUBMIT>
</FORM>
</body>
</html>
try
{
file = new String(dataBytes);
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=/" + 1);
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 folder = "/tmp/uploads/";
fileOut = new FileOutputStream(folder + saveFile);
fileOut.write(dataBytes);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
}
catch(Exception e)
{
out.print(e);
}
finally
{
try{fileOut.close();}catch(Exception err){}
}
}
%>
Please note that this is not a final thing and is subject to revision. Feel free to do so.
Thank you