Implement file upload with servlvet

zhaozj2021-02-08  197

// File Upload Module // IT Cannot Handle Nested Data // OR Internationalized Content (SUCH AS NON LATIN-1 Filenames).

//// designed by Mouse King, Last Modified On August 2nd, 2000 // File Upload A File // You Can Customize The File Size, Now IT IS 5M // The FTP Server Target Path IS / USR / local / jakarta-tomcat / bin.

Package BBS;

Import java.io. *; import java.util. *; import javax.servlet. *; import javax.servlet.http. *;

Public class uploadtest extends httpservlet {string rootpath, surcessMessage

Static Final Int Max_size = 102400; Public Void Init (ServletConfig Config) Throws servletexception {super.init (config);

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType ( "text / html"); PrintWriter out = new PrintWriter (response.getOutputStream ()); out.println ( ""); Out.println (" servlet1 </ title> </ head>"); out.println ("<body> <form eNctype = /" multipart / form-data / "method = post action = ' '> <input type = file enctype = / "Multipart / form-data /" name = filedata> "); out.println (" <input type = submit> </ form> "); Out.println (" </ Body> </ html> "); out.close ();</p> <p>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 output stream in case we are unable to redirect client * / response.setContentType ( "text / plain"); out = response.getOutputStream ();} catch (IOException e) {// print error message to standard out System.out.println ( "error output stream getting."); System.out.println ("Error Description:" E); Return;}</p> <p>Try {string contentType = Request.getContentType (); // made sure content type is multipart / form-data = Null && contenttype.indexof ("Multipart / Form-Data")! = -1) {///// open input stream from client to capture upload file in = new DataInputStream (request.getInputStream ()); // get length of content data int formDataLength = request.getContentLength (); // allocate a byte array to store content data byte dataBytes [ ] = new byte [formDataLength]; // read file into byte array int bytesRead = 0; int totalBytesRead = 0; int sizeCheck = 0; while (totalBytesRead <formDataLength) {// check for maximum file size violation sizeCheck = 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 manipu lation String file = new String (dataBytes); // since byte array is stored in string, release memory dataBytes = null; / * get boundary value (boundary is a unique string that separates content data) * / int lastIndex = contentType.lastIndexOf ("="); String boundary = contenttype.substring (LastIndex 1, ContentTy.Length ()); // Get Directory Web Variable from Request String Directory = ""; if (file.indexof ("name = /" Directory / "" ""> 0) {Directory = file.substring (file.indexof ("name = /" directory / "));</p> <p>// remove carriage return directory = directory.substring (directory.indexOf ( "/ n") 1); // remove carriage return directory = directory.substring (directory.indexOf ( "/ n") 1); // Get Directory Directory = Directory.substring (0, Directory.indexof ("/ n") - 1); / * make Sure User Didn't Select a Directory Higher In The Directory Tree * / if (Directory.indexof ".. ")> 0) {Out.println (" Security Error: You can't UPLOAD " " to a directory higher in the directory tree. "); Return;}} // get success,}} // Get SUCCESSPAGE Web Variable from Request string SuccessPage =" "; If (file.indexof (" name = / "success /")> 0) {success.indexof (file.indexof ("name = /" successpage / ")); // Remove carriage return SUCCESSPAGE = successPage.substring (successPage.indexOf ( "/ n") 1); // remove carriage return successPage = successPage.substring (successPage.indexOf ( "/ n") 1); // get success page successPage = successPage .substring (0, successpage.indexof ("/ n") - 1);} // Get OverWrite Flag Web Variable from Request string overwrite; if (file.indexof ("name = /" overwrite / ")> 0) {OverWrite = file.substring (file.indexof (" name = / "overwrite /") ; // remove carriage return overWrite = overWrite.substring (overWrite.indexOf ( "/ n") 1); // remove carriage return overWrite = overWrite.substring (overWrite.indexOf ( "/ n") 1); overWrite = OverWrite.Substring (0, OverWrite.indexOf ("/ n") - 1);} else {OverWrite = "false";</p> <p>} // get overwritepage web variable from request string overwritepage = ""; if (file.indexof ("name = /" overwritepage / ")> 0) {OverwritePage = file.substring (" name = / " overWritePage / "")); // remove carriage return overWritePage = overWritePage.substring (overWritePage.indexOf ( "/ n") 1); // remove carriage return overWritePage = overWritePage.substring (overWritePage.indexOf ( "/ n" ) 1); // get overwrite page overwritepage = overwritepage.substring (0, overwritepage.indexof ("/ n") - 1);} // Get filename of upload file string savefile = file.substring (file.indexof "filename = /" ") 10); savefile = savefile.substring (0, savefile.indexof (" / n ")); savefile = savefile.substring (SaveFile.lastIndexof (" // ") 1, Savefile. IndexOf ("/")); / * Remove Boundary Markers and other multipart / form-data tags from beginning of upload file section * / int pos; // position in Upload file // Find position of Upload File Section of Request POS = file.indexof ("filename = /" "); // Find position of content-DISPO SpitLine Pos = file.indexof ("/ n", POS) 1; // Find position of content-type line pos = file.indexof ("/ n", pos) 1; // Find position of Blank Line POS = file.indexof ("/ n", pOS) 1; / * Find the location of the next boundary marker (Marking the end) * / int boundaryLocation = file.indexof (Boundary, POS) 4; // Upload File LIES BETWEEN POS AND BoundaryLocation File = file.substring (POS, BoundaryLocation); // Build The Full Path of the Upload File String FileName =</p> <p>new String (rootPath directory saveFile); // create File object to check for existence of file File checkFile = new File (fileName); if (checkFile.exists ()) {/ * file exists, if OverWrite flag is off, Give message and abort * / if (! overwrite.tolowercase (). Equals ("true")) {if (overwritepage.equals (")) {/ * Overwrite HTML Page URL NOT Received, respond with generic message * / out .println ( "Sorry, file already exists.");} else {// redirect client to OverWrite HTML page response.sendRedirect (overWritePage);} return;}} / * create File object to check for existence of Directory * / File fileDir = new File (rootPath directory); if (! fileDir.exists ()) {// Directory does not exist, create it fileDir.mkdirs ();} // instantiate file output stream fileOut = new FileOutputStream (fileName) ; // Write the string to the file as a byte array fileout.write (file.getbytes (), 0, file.Length ()); if (SuccessPage.equals (")) {/ * success html page url not NOT Received, Respond with eneric success message * / out.println (successMessage); out.println ( "File written to:" fileName);} else {// redirect client to success HTML page response.sendRedirect (successPage);}} else // request IS Not Multipart / Form-Data {// Send Error Message To Client Out.println ("Request Not Multipart / Form-Data);}} Catch (Exception E) {Try {// Print Error Message To Standard Out System .out.println ("ERROR in dopost: e); // send Error Message to Client Out.println (" An Unexpected Error Has Occurred. "); Out.println (" Error Description: " E);} Catch (Exception F) {}} finaryly {try} finary-</p> <p>// 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) {}}}}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-3010.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="3010" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.039</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'hTJU_2FUZrGb3_2F2LYRoLC4KZ6ZYpnULyy2VI8xrBYf9C1hUSXOrCnZxU_2BE2bJ2ofFvuv8IhC6XJcm2_2BYMV2Ygvag_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>