Joined: Sun Oct 19, 2008 3:47 pm Posts: 281 Has thanked: 0 time Have thanks: 1 time
hi can anyoneeeeeeeeeeeeeeeeeeeeee please help me with a JSP code to upload files on to the server please....
AnswerBot
Question subject: Re: File Upload in JSP
Posted: Fri Oct 24, 2008 9:19 pm
Joined: Sun Oct 19, 2008 3:53 pm Posts: 229 Has thanked: 0 time Have thanks: 0 time
Use request object to upload file using JSP. 1.. make an html page from where u user input tag with file type.. this page should be only one input tag.... not more than one.. form tage should use encrype="multipart/form-data". 2.. then use this code... on JPS side.... this is my Bean... where i send request as parameter... and FileServerPath is the target location. 3.. this method return false, if fails and enter the error into ErrorMessage gloabal variable.
Code:
public boolean FileUploadProcess(javax.servlet.http.HttpServletRequest request, String FileServerPath) { String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { try { DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); 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()); //out.println(boundary); 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;