Write your own file upload components in the Java environment

zhaozj2021-02-16  58

Write your own file upload components in the Java environment

The upload file is often used, the file upload principle in the B / S environment is actually like an accessory, and the HTTP data is composed of file data, and you only get the data stream to remove its iconic data. The rest is your data file, and complete it uploaded by writing it.

Below we are distributed:

1. Upload the static page of the file, we must confirm why Method = "post" encType = "multipart / form-data" should not say it.

<% @ Page ContentType = "Text / HTML; Charset = GBK"%> browsefile </ title> </ head></p> <p><body> <h1> test2 </ h1> <form method = "post" encType = "multipart / form-data" Action = "ifileupload.jsp"> <input name = "filea" type = "file"> <br > <Input name = "btnval" type = "submit" value = "Upload"> <input type = "reset" value = "reset"> </ form></p> <p></ body> </ html></p> <p>After the client is uploaded, the server-side data flow tail format is as follows, here uploaded a Word document</p> <p>Let's take a look at the head of the data stream:</p> <p>---------------------------- 7D22F821706E0Content-disposition: form-data; name = "filea"; filename = "C: / work The overall design of the stream management system.doc "Content-Type: Application / MSWORD Xing Wei ?? ... (Note that this is where the data file begins) ............... .......................</p> <p>Tail mark:</p> <p>---------------------------- 7D22F821706E0Content-disposition: form-data; name = "btnval" upload ------- ---------------------- 7D22F821706E0 -</p> <p>So we get up the tail signature data we get uploaded file data.</p> <p>Let's take a look at the process of uploading Bean: UploadBean first gets the initialization bean gets the context environment:</p> <p>public final void initialize (PageContext pageContext) throws ServletException {m_application = pageContext.getServletContext (); m_request = (HttpServletRequest) pageContext.getRequest (); m_response = (HttpServletResponse) pageContext.getResponse ();}</p> <p>Written the data into a BYTES array, the array size is the size of the Request stream. m_totalBytes = m_request.getContentLength (); m_binArray = new byte [m_totalBytes]; for (; totalRead <m_totalBytes; totalRead = readBytes) try {m_request.getInputStream (); readBytes = m_request.getInputStream () read (m_binArray, totalRead,. M_TotalBytes - TotalRead;} ​​Catch (Exception E) {System.out.Println ("Unable to Upload Data."); E.PrintStackTrace ();} 2. Here, you will start processing bytes arrays.</p> <p>I used to see some netizens to convert M_BinArray directly into string, then use String method to remove flag data.</p> <p>String newstr = new string (m_binarray);</p> <p>I have tried this way, it is not good, I don't know if they test the process, there should be no problem for the upload text file. If the upload is the Word document or the picture, the data is converted to the string. There will be lost, I think it may be due to the reason for the coding, so it cannot be directly converted.</p> <p>The correct way is to convert each bit of the byte array into a char or to determine the ASCII code value to determine the head flag as data:</p> <p>for (;! found && m_currentIndex <m_totalBytes; m_currentIndex ) {if (m_binArray [m_currentIndex] == 13) found = true; else m_boundary = m_boundary (char) m_binArray [m_currentIndex];} if (m_currentIndex == 1) return; m_currentIndex ; do {if (m_currentIndex> = m_totalBytes) break; dataHeader = getDataHeader (); System.out.println (dataHeader); m_currentIndex = m_currentIndex 2; isFile = dataHeader.indexOf ( "filename")> 0; getDataSection () ; If (isfile) {system.out.println ("-----> m_startdata:" m_startdata); system.out.println ("---> m_enddata:" m_enddata); try {fileout = New fileoutp UtStream ("c: //test11.doc"); fileout.write (m_binarray, m_startdata 1); fileout2 = new fileoutputstream ("c: //test00.doc"); fileout2.write (m_binarray) Catch (Exception E) {system.out.println ("Unable to write data to test file."); E.PrintStackTrace ();} finally {type {fileout.close ();</p> <p>Fileout2.close ();} catch (exception e) {E.PrintStackTrace ();}}} private string getDataHeader () {int starter () {int start = m_currentIndex; int end = 0; int LEN = 0; boolean found = false; while ! found) if (m_binArray [m_currentIndex] == 13 && m_binArray [m_currentIndex 2] == 13) {found = true; end = m_currentIndex - 1; m_currentIndex = m_currentIndex 2;} else {m_currentIndex ;}</p> <p>String DataHeader = new string (m_binarray, start, (end - start) 1); Return DataHeader;</p> <p>}</p> <p>private void getDataSection () {boolean found = false; String dataHeader = new String (); int searchPos = m_currentIndex; int keyPos = 0; int boundaryLen = m_boundary.length (); m_startData = m_currentIndex; m_endData = 0; do {if ( SearchPos> = m_totalbytes) Break; if (m_binarray [searchpos] == (byte) m_boundary.charat (keypos)) {if (keypos == Boundarylen - 1) {m_enddata = ((SearchPos - Boundarylen) 1) - 3; Break;} searchPOS ; keypos ;} else {searchPos ; keypos = 0;}} while; m_currentIndex = m_enddata boundarylen 3;} m_currentIndex is current word The pointer position of the array, first get the header data, see how to getDataHeader () then get the pointer position and size started by the file data, see method getDatasection (), then write data to file: fileout.write (m_binarray, m_startdata M_ENDDATA-M_STARTDATA 1); a complete data file, Test00.doc and test11.doc are files written by the data streams before and after the flag data, and everyone can see the differences in the binary view program.</p> <p>The above getDataHeader (), getDatasection () is the implementation principle of SmartUpload, where the method of analyzing the marking data bit is slightly complicated, and netizens can analyze themselves. The program is tested under Tomcat, and there is no problem with the uploading Word documentation and pictures.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-24317.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="24317" 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 = '3SzgRGwxjSiW0bhaaLUxGzQMMvbv6VMnUiH03LVJN8_2FfoEjDpnmTdq86ngaCTf8bISxWI7RcSZhu2fUbz0CCRw_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>