如何在Web页上实现文件上传

发布时间:2024-02-28 17:22:46
if (document.all!=null){ if (typeof(parent.parent.BoardTitle)!='undefined') if (typeof(parent.parent.BoardTitle.setCount)!="undefined") parent.parent.BoardTitle.setCount(179)} function ExpandMe(){ if (typeof(parent.frmMain)!="undefined") { parent.frmMain.rows="45,*" } } // document.onclick = ExpandMe // ExpandMe() document.write(""); document.write(""); document.write("");

public class UploadServlet extends HttpServlet{//default maximum allowable file size is 100kstatictictic final int MAX_SIZE = 102400;//instance variables to store root and success messageString rootPath, successMessage;/*** init method is called when servlet is initialized.*/public void init(ServletConfig config) throws ServletException{super.init(config);//get path in which to save filerootPath = config.getInitParameter("RootPath");if (rootPath == null){rootPath = "/";}/*Get message to show when upload is complete. Used only ifa success redirect page is not supplied.*/successMessage = config.getInitParameter("SuccessMessage");if (successMessage == null){successMessage = "File upload complete!";}}/*** doPost reads the uploaded data from the request and writes* it to a file.*/public void doPost(HttpServletRequest request,HttpServletResponse response){ServletOutputStream out=null;DataInputStream in=null;FileOutputStream fileOut=null;try{/*set content type of response and get handle to outputstream in case we are unable to redirect client*/response.setContentType("text/plain");out = response.getOutputStream();}catch (IOException e){//print error message to standard outSystem.out.println("Error getting output stream.");System.out.println("Error description: " + e);return;}try{//get content type of client requestString contentType = request.getContentType();//make sure content type is multipart/form-dataif(contentType != null && contentType.indexOf("multipart/form-data") != -1){//open input stream from client to capture upload filein = new DataInputStream(request.getInputStream());//get length of content dataint formDataLength = request.getContentLength();//allocate a byte array to store content databyte dataBytes[] = new byte[formDataLength];//read file into byte arrayint bytesRead = 0;int totalBytesRead = 0;int sizeCheck = 0;while (totalBytesRead < formDataLength){//check for maximum file size violationsizeCheck = totalBytesRead + in.available();if (sizeCheck > MAX_SIZE){out.println("Sorry, file is too large to upload.");return;}bytesRead = in.read(dataBytes, totalBytesRead,formDataLength);totalBytesRead += bytesRead;}//create string from byte array for easy manipulationString file = new String(dataBytes);//since byte array is stored in string, release memorydataBytes = null;/*get boundary value (boundary is a unique string thatseparates content data)*/int lastIndex = contentType.lastIndexOf("=");String boundary = contentType.substring(lastIndex+1,contentType.length());//get Directory web variable from requestString directory="";if (file.indexOf("name=\"Directory\"") > 0){directory = file.substring(file.indexOf("name=\"Directory\""));//remove carriage returndirectory = directory.substring(directory.indexOf("\n")+1);//remove carriage returndirectory = directory.substring(directory.indexOf("\n")+1);//get Directorydirectory = directory.substring(0,directory.indexOf("\n")-1);/*make sure user didn't select a directory higher inthe directory tree*/if (directory.indexOf("..") > 0){out.println("Security Error: You can't upload " +"to a directory higher in the directory tree.");return;}}//get SuccessPage web variable from requestString successPage="";if (file.indexOf("name=\"SuccessPage\"") > 0){successPage = file.substring(file.indexOf("name=\"SuccessPage\""));//remove carriage returnsuccessPage = successPage.substring(successPage.indexOf("\n")+1);//remove carriage returnsuccessPage = successPage.substring(successPage.indexOf("\n")+1);//get success pagesuccessPage = successPage.substring(0,successPage.indexOf("\n")-1);}//get OverWrite flag web variable from requestString overWrite;if (file.indexOf("name=\"OverWrite\"") > 0){overWrite = file.substring(file.indexOf("name=\"OverWrite\""));//remove carriage returnoverWrite = overWrite.substring(overWrite.indexOf("\n")+1);//remove carriage returnoverWrite = overWrite.substring(overWrite.indexOf("\n")+1);//get overwrite flagoverWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);}else{overWrite = "false";}//get OverWritePage web variable from requestString overWritePage="";if (file.indexOf("name=\"OverWritePage\"") > 0){overWritePage = file.substring(file.indexOf("name=\"OverWritePage\""));//remove carriage returnoverWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);//remove carriage returnoverWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);//get overwrite pageoverWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);}//get filename of upload fileString saveFile = file.substring(file.indexOf("filename=+10;saveFile = saveFile.substring(0,saveFile.indexOf("\n"));saveFile = saveFile.substring(saveFile.lastIndexOf(\\saveFile.indexOf("""";/*remove boundary markers and other multipart/form-datatags from beginning of upload file section*/int pos; //position in upload file//find position of upload file section of requestpos = file.indexOf("filename=\"");//find position of content-disposition linepos = file.indexOf("\n",pos)+1;//find position of content-type linepos = file.indexOf("\n",pos)+1;//find position of blank linepos = file.indexOf("\n",pos)+1;/*find the location of the next boundary marker(marking the end of the upload file data)*/int boundaryLocation = file.indexOf(boundary,pos)-4;//upload file lies between pos and boundaryLocationfile = file.substring(pos,boundaryLocation);//build the full path of the upload fileString fileName = new String(rootPath + directory +saveFile);//create File object to check for existence of fileFile checkFile = new File(fileName);if (checkFile.exists()){/*file exists, if OverWrite flag is off, givemessage and abort*/if (!overWrite.toLowerCase().equals("true")){if (overWritePage.equals()*OverWrite HTML page URL not received, respondwith generic message*/out.println("Sorry, file already exists.");}else{//redirect client to OverWrite HTML pageresponse.sendRedirect(overWritePage);}return;}}/*create File object to check for existence ofDirectory*/File fileDir = new File(rootPath + directory);if (!fileDir.exists(){/////)Directory doesn't exist, create itfileDir.mkdirs();}//instantiate file output streamfileOut = new FileOutputStream(fileName);//write the string to the file as a byte arrayfileOut.write(file.getBytes(),0,file.length());if (successPage.equals()*success HTML page URL not received, respond withgeneric success message*/out.println(successMessage);out.println("File written to: " + fileName);}else{//redirect client to success HTML pageresponse.sendRedirect(successPage);}}else //request is not multipart/form-data{//send error message to clientout.println("Request not multipart/form-data.");}}catch(Exception e){try{//print error message to standard outSystem.out.println("Error in doPost: " + e);//send error message to clientout.println("An unexpected error has occurred.");out.println("Error description: " + e);}catch (Exception f) {}}finally{try{fileOut.close(); //close file output stream}catch (Exception f) {}try{in.close(); //close input stream from client}catch (Exception f) {}try{out.close(); //close output stream to client}catch (Exception f) {}}}}

上一篇 Java中的两个特殊变量this和super
下一篇 JAVA的网络功能与编程 二

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题