#fileload.py #File Upload Servlet #This Servlet Uploads a file from the client machine #into the Directory in Server box where it runs #This File Upload Servlet works for both binary as well as text files from javax import servlet from javax.servlet import http from java.io import * from java.util import * from java.lang import * from jarray import array , zeros import string , pickle , os #Server IP and Port address SERVER_IP = "127.0.0.1" SERVER_PORT = "8080" #Global variables to have session details session_id = 0 session = 0 done = 0 #done is a flag to indicate that the request from the client has been processed def sub_array ( main_array , end_array ): #This function returns the index within main_array where the end_array #which is embedded within the main_array starts #If no such array is embedded , it returns -1 i = len (main_array) - 1 k = len (end_array) - 1 while 1: j = k while ( j >= 0 ): if ( end_array[j] == main_array[i] ): i = i - 1 j = j - 1 if ( j < 0 ): j = - 1 break if ( i >= 0 ): continue else: return (-1) else: break if ( j == -1 ): return ( i + 1 ) else: i = i - 1 if ( i >= 0 ): continue else: return (-1) class fileload (http.HttpServlet): def doGet(self, req, res): global session , session_id , done done = 0 #Get all Request parameters and Convert it to Java String format parameters = str(req.getParameterNames()) parameters = String(parameters) #Check if there are no parameters parameters = parameters.indexOf("EmptyEnumerator") #If there are no request parameters, the default Login screen is displayed if parameters != -1: res.setContentType("text/html") toclient = res.getWriter() toclient.println( "File Upload Servlet" + "

 

 

UserID    
Password


""") done = 1 #Finished with Processing the client #If User ID and Password were provided, the file Upload screen is displayed UID = req.getParameter("userid") password = req.getParameter("password") if (done == 0 and UID != None and password != None): if UID == "admin" and password == "admin": session = req.getSession() session_id = session.getId() res.setContentType("text/html") toclient = res.getWriter() toclient.println( "
" """Enter the name of the File
""") URL = "http://" + SERVER_IP + ":" + SERVER_PORT + req.getRequestURI() + "?logout=1" toclient.println("") toclient.println ("Logout") toclient.println("") else: #Authentication failed res.setContentType("text/html") toclient = res.getWriter() toclient.println("") toclient.println("
Authentication failed ") URL = "http://" + SERVER_IP + ":" + SERVER_PORT + req.getRequestURI() toclient.println("") toclient.println ("
Goto LOGIN page
") toclient.println("") done = 1 #Finished with Processing the client logout = req.getParameter("logout") if ( done == 0 and logout != None ): #User logs out, Current Session Invalidated try: session.invalidate() session_id = 0 res.setContentType("text/html") toclient = res.getWriter() toclient.println("") toclient.println("
You are Logged out") URL = "http://" + SERVER_IP + ":" + SERVER_PORT + req.getRequestURI() toclient.println("") toclient.println ("
Goto LOGIN page
") toclient.println("") except: #Logout attempted after a session was already invalidated (Invalid session) res.setContentType("text/html") toclient = res.getWriter() toclient.println("") toclient.println("
Invalid session") URL = "http://" + SERVER_IP + ":" + SERVER_PORT + req.getRequestURI() toclient.println("") toclient.println ("
Goto LOGIN page
") toclient.println("") def doPost (self, req, res): global done #Flag to indicate that the request has been processed done = 0 #Set Response type res.setContentType("text/html") contentType = req.getContentType() #Content-type (multipart/form-data) toclient = res.getWriter() #To write response to the client (Browser) if session_id == 0: #Trying to upload file in an invalid session toclient.println("") toclient.println("
Invalid session") URL = "http://" + SERVER_IP + ":" + SERVER_PORT + req.getRequestURI() toclient.println("") toclient.println ("
Goto LOGIN page
") toclient.println("") done = 1 #Finished with Processing the client if done == 0 and req.getContentLength() > 2000000: #If Content length exceeds 2000000 bytes, File Size exceeded message #is displayed toclient.println( "") toclient.println(" File size exceeded ") toclient.println(" " ) done = 1 if done == 0: #Get a new Stream for processing POST data contents input = DataInputStream ( req.getInputStream() ) length = req.getContentLength() #Get the exact path of the File (with respect to client system) uploaded list = [] for i in range (4): #These lines of the POST data contents contains header #string, name of the file , etc list.append ( input.readLine() ) boundary = String(list[0]).getBytes() join_list = string.join(list[1], "" ) #boundary variable gets the unique Header String (Which also appears at the end) #This String is used to extract the Data portion of the file from the #Stream #Getting the Path information of the File uploaded filepath = join_list[string.rfind(join_list,"=")+2:len(join_list)-1] if filepath == "": #No file was selected , Prompt for a File to be uploaded toclient.println( "") toclient.println(" Please Select a file to upload ") toclient.println(" " ) else: #Get the exact name of the file which was uploaded (from the path) filename = filepath[string.rfind(filepath,os.sep)+1:] exactfilename = filename #os.sep is used in the above call so that the path separation characters #for different platforms can be used to separate the file name from its path #for example \ or / for Windows / for UNIX, etc #Create new Java byte array and initialize it to zero buffer = zeros ( length , 'b' ) bytesread = 0 # Keep track of bytes read #Read the entire bytes in the buffer try: while (1): #Copy the contents in a buffer buffer[bytesread] = input.readByte() bytesread = bytesread + 1 except: pass input.close() # Close the Input Stream #Write_boundary determines the index at which #the data portion of the file uploaded ends write_boundary = sub_array ( buffer , boundary ) #The sub_array function defined above returns an index within a #main array till the start of another array (here boundary) is reached #This is done to get the contents of data portion of the file #from the whole array which is read from the DataInputStream #i.e to separate file contents from the end header filename = os.path.dirname(req.getRealPath(req.getServletPath())) +"//"+ filename #The above call is used to create the uploaded file in the same directory #where the servlet runs #Create a New OutputStream output = DataOutputStream ( FileOutputStream (filename)) #Now write the data portion of the file in the OutputStream for i in range (write_boundary-2): output.write (buffer[i]) output.close() #Deallocate the buffer buffer = None toclient.println( "") toclient.println("File " + exactfilename + " Uploaded" ) toclient.println(" " ) #Prompt the user in case of more file Uploads if session_id != 0: toclient.println( "
" """Enter the name of the File
""") URL = "http://" + SERVER_IP + ":" + SERVER_PORT + req.getRequestURI()+ "?logout=1" toclient.println("") toclient.println ("Logout") toclient.println("")