JAKATA upload file

xiaoxiao2021-03-06  20

The function of the upload file is often seen in the webpage. This looks very common in the servlet api! It is really sunny to beginners !! Fortunately, Java's world, always have Free big dinner can be eaten! There are many people on the Internet API on the Internet API. Here is to introduce it.

Apache provided by Apache.

Apache's API can go

Http://jakarta.apache.org/commons/fileupload/ download, API instructions can be referred to

http://jakarta.apache.org/commons/fileupload/apidocs/index.html Takes a slightly changed version of the example provided by Apache and simple explanation.

If you want to upload a file, you must write this ...

ENCTYPE = 'Multipart / Form-data' method = 'post' action = 'myservlet'>

TYPE = 'file' name = 'thefile1'>

TYPE = 'file' name = 'thefile2'>

It is necessary to pay special attention to some red part, and you can generate the following web page, the user can select the "Browse" button to select the file you want to upload, and then press "Upload" to upload the file, which is responsible for receiving by myServlet. Why do you want to write this? Interested people can refer to your own

RFC 1867.

Next, let's see how myServlet write ...

Import javax.servlet.servlet;

Import javax.servlet.servletException;

Import java.util. *;

Import javax.servlet.http.httpservlet;

Import javax.servlet.http.httpservletRequest;

Import javax.servlet.http.httpservletResponse;

Import org.apache.commons.fileupload. *;

Public class myservlet extends httpservlet imports servlet {

Public void dopost (httpservletRequest Req, httpservletResponse resp) throws servletexception, ioException {

DiskfileUpload FU = New DiskfileUpload ();

Fu.setSizeMax (10000000); // Uploaded files can be 1000000 BYtes

Fu.setsizetHold (4096); // You can have 4096 bytes in Memery, Cache

Fu.SetRepositoryPath ("/"); // The signal is greater than getsizethreshold

List fileItems = null;

Try {

FileItems = Fu.Parsequest (REQ);

} catch (fileUploadexception e) {

E.PrintStackTrace ();

}

Iterator i = fileItems.Item ();

While (I.hasNext ()) {fileItem Fi = (fileItem) i.next ();

String filename = getFileName (fi.getname ()); //fi.getname () get the file name containing the path

File f = new file ("/ upload /" filename);

Try {

FI.WRITE (F); // Write the file to disk

} catch (exception E1) {

E1.PrintStackTrace ();

}

}

}

// filter the path and only pass the file name

Public String getFileName (String Fullname) {

String filename = NULL;

Fullname = fullname.replace ('//', '/');

StringTokenizer token = new stringtokenizer (fullname, "/");

While (token.hasmoreToKens ()) {

Filename = token.nextToken ();

}

Return FileName;

}

}

Section 01 FileUpload Overview When writing a website program, there is often not only a pure text communication between Client and Server, and there will be binary file transfer. How to transfer it in HTML Form, you must follow

RFC 1867 is specified.

Basically, post.jsp should have a similar HTML TAG below:

Input Your name:

Select the file:

This part is a category of HTML, interested in drilling RFC ...

Section 02 MULTIPART / FORM-DATA's HTTP performance scenario When you press to transfer, Browser will send Post's information to Server,

Post http: // localhost: 9000 / fileupload / upload.jsp http / 1.1 accept: image / gif, image / x-xbitmap, image / jpeg, image / pjpeg, application / vnd.ms-powerPoint, Application / VND.MS -Excel, Application / MSWORD, * / * REFERER: http: // localhost: 9000 / fileupload / post.jsp accept-language: zh-tw, zh-cn; q = 0.7, en-us; q = 0.3 Content- TYPE: MULTIPART / FORM-DATA; Boundary = -------------------------- 7D33E580784 Accept-Encoding: gzip, deflate user-agent: mozilla /4.0 (compatible; MSIE 6.0; Windows NT 5.0) Host: www.softleader.com.tw Content-Length: 3020 Connection: Keep-Alive Cache-Control: no-cache Cookie: JSESSIONID = 3B31F07F56328E7B623A9BA1C4E3479D we can know, Contenet-Type It is also the transfer of Boundary in the use of multipart / form-data. Examples of SECTION 03 File.html by Lin Jie

file upload </ title></p> <p><meta http-equiv = "content-type" content = "text / html; charSet = big5"></p> <p></ hEAD></p> <p><body bgcolor = "# ffffff" text = "# 000000"> <p> <font size = "5" color = "# ff0000"></p> <p><b> Chapter 7 Archive Upload Example </ b> </ font> </ p></p> <p><form name = "form1" enctype = "multipart / form-data" method = "post" action = "jyfile.jsp"></p> <p><p> Upload file 1: <input type = "file" name = "file1" size = "20" maxlength = "20"> </ p></p> <p><p> Archive 1 Narrative: <input type = "text" name = "file1" size = "30" maxlength = "50"> </ p></p> <p><p> Upload file 2: <input type = "file" name = "file2" size = "20" maxlength = "20"> </ p></p> <p><p> Archive 2 Narrative: <input type = "text" name = "file2" size = "30" maxlength = "50"> </ p> <p> upload file 3: <input type = "file" name = "File3" size = "20" maxlength = "20"> </ p></p> <p><p> Archive 3 Narration: <input type = "text" name = "file3" size = "30" maxlength = "50"> </ p></p> <p><p> <input type = "submit" value = "Upload"> <input type = "reset" value = "Clear"> </ p></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Section 04 Transfer format</p> <p>Post /neWSpaper/JYFILE.JSP HTTP / 1.1</p> <p>Accept: Image / GIF, Image / X-Xbitmap, Image / JPEG, Image / PJPEG,</p> <p>Application / VND.ms-PowerPoint, Application / VND.ms-Excel, Application / Msword, * / *</p> <p>Referer: http: // localhost: 9000 / newspaper / jyfile.html</p> <p>Accept-language: zh-tw, zh-cn; q = 0.7, en-us; q = 0.3</p> <p>CONTENT-TYPART / FORM-DATA; Boundary = --------------------------- 7D31091C6205FC</p> <p>Accept-encoding: Gzip, deflate</p> <p>User-agent: mozilla / 4.0 (compatible; msie 6.0; windows NT 5.0)</p> <p>Host: Localhost: 9000</p> <p>Content-Length: 428583</p> <p>Connection: Keep-alive</p> <p>Cache-Control: No-cache</p> <p>Cookie: jsessionid = E141744815A8FF44F8AA9BA6D5946710</p> <p>---------------------------- 7D31091C6205FC</p> <p>Content-disposition: form-data; name = "file1"; filename = "C: / TEST / Test .exe"</p> <p>Content-Type: Application / OcTet-stream</p> <p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (binary garbled)</p> <p>---------------------------- 7D31091C6205FC</p> <p>Content-disposition: form-data; Name = "file1"</p> <p>EXE</p> <p>---------------------------- 7D31091C6205FC</p> <p>Content-disposition: form-data; name = "file2"; filename = "c: / test / test .gif" Content-Type: image / gif</p> <p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (binary garbled)</p> <p>---------------------------- 7D31091C6205FC</p> <p>Content-disposition: form-data; Name = "file2"</p> <p>GIF</p> <p>---------------------------- 7D31091C6205FC</p> <p>Content-disposition: form-data; name = "file3"; filename = "c: / test / test.xls"</p> <p>Content-Type: Application / VND.MS-Excel</p> <p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (binary garbled)</p> <p>---------------------------- 7D31091C6205FC</p> <p>Content-disposition: form-data; name = "file3"</p> <p>XLS</p> <p>----------------------------- 7D31091C6205FC -</p> <p>Section 05 is sent to JYFILE.JSP upload processing by jiayun</p> <p><% @ Page ContentType = "text / html; charset = big5" language = "java"%></p> <p><% @ Page Import = "java.io. *"%></p> <p><% @ Page Import = "java.util. *"%></p> <p><% @ page import = "org.apache.commons.fileUpload. *"%></p> <p><%</p> <p>// Declare the file to place the file to the server / .... / upload directory</p> <p>String savedirectory = "c: //";</p> <p>/ / Declaration Temporary Directory</p> <p>String tmpdirectory = "c: //";</p> <p>// Declaration to the total size of the files, the unit is BYTE, -1 means unlimited</p> <p>INT MAXPOSTSIZE = 1024 * 1024;</p> <p>%></p> <p><%</p> <p>// Declare a variable in which the store is described</p> <p>String FileDescription = NULL;</p> <p>// Declare a variable in the store name</p> <p>String filename = NULL;</p> <p>// Declare the variables of the stored upload file size</p> <p>Long filesis = 0;</p> <p>// Declare the variables of the stored upload file</p> <p>String contentType = NULL;</p> <p>/ / Calculate the number of uploaded files</p> <p>INT count = 0;</p> <p>%></p> <p><%</p> <p>DiskfileUpload Upload ();</p> <p>// Set the size of the memory store, exceed the write file, have a set temporary directory, the temporary file is placed in the temporary directory</p> <p>Upload.setsizethreshold (4096);</p> <p>/ / Set the total upload size limit</p> <p>Upload.setsizemax;</p> <p>// Set the temporary directory</p> <p>Upload.setRepositoryPath (TMPDIRECTORY);</p> <p>List / * fileItem * / items = UPLOAD.PARSEREQUEST (REQUEST);%></p> <p><body></p> <p><%</p> <p>Iterator it = items.iterator ();</p> <p>INT TMP = 0;</p> <p>FileItem TmpInm = NULL;</p> <p>While (item.hasnext ())</p> <p>{</p> <p>TMP ;</p> <p>FILEITEM ITEM = (FileItem) iter.next ();</p> <p>IF (item.isformfield ()) {</p> <p>// If it is a general field, get a file narrative</p> <p>FileDescription = item.getstring ();</p> <p>} else {</p> <p>/ / Otherwise get a file information</p> <p>FILENAME = item.getname ();</p> <p>// Because different browsers will pass Path FileName, some only FileName</p> <p>Try {</p> <p>// for Wintel Platform</p> <p>FILENAME = filename.substring (filename.lastindexof ("//") 1);</p> <p>// for UNIX-LIKE Platform</p> <p>FileName = filename.substring (filename.lastindexof ("/") 1);</p> <p>} catch (exception ex) {</p> <p>Out.println (ex);</p> <p>}</p> <p>ContentType = item.getContentType ();</p> <p>FileSize = item.getsize ();</p> <p>TmpItem = Item;</p> <p>}</p> <p>// Because a file is two fields, each read two fields are handled once</p> <p>IF (TMP == 2 && FileSize! = 0)</p> <p>{</p> <p>COUNT ;</p> <p>%></p> <p><font color = "red"> You uploaded by <% = count%> profile: </ font> <br></p> <p>The file name is: <% = filename%> <br></p> <p>The size of the file is: <% = filesize%> Bytes <br></p> <p>Archive type: <% = contenttype%> <br></p> <p>Description file: <% = FileDescription%> <br> <br></p> <p><%</p> <p>// write the archive into the archive directory</p> <p>Try {</p> <p>Out.println (filename);</p> <p>FILE UPLOADEDFILE = New File (SaveDirectory FileName);</p> <p>TmpItem.write (UPLOADEDFILE);</p> <p>} catch (exception ex) {</p> <p>Out.println (ex);</p> <p>}</p> <p>TMP = 0;</p> <p>} else if (tmp == 2 && filesis == 0) {</p> <p>TMP = 0;</p> <p>} // end if</p> <p>} // End while</p> <p>%></p> <p>You have uploaded <font color = "red"> <% = count%> </ font> file</p> <p></ body></p> <p></ html></p> <p>Jia Xiaoshi is very clear about the annotation, and the people who have the heart carefully ~~~</p> <p>Section 06 Struts FileUpload why struts 1.1 should wait for Commons-fileUpload 1.0 because Struts has a subpackage called org.apache.struts.upload. *; This is the setting related File Format If you use strut for MVC framework, you can refer to Example in EXAMPLE Development of Struts-Upload.war</p> <p>(1) Establish UPLOAD.JSP</p> <p><html: form action = "Upload.do?queryparam=su" ENCTYPE = "Multipart / Form-Data"></p> <p>Archive Narration: <HTML: Text Property = "THETEXT" /> <br></p> <p>Select Archive: <HTML: File Property = "Thefile" /> <br></p> <p></ html: form></p> <p>(2) Establish uplineform.java</p> <p>Public class uploadform extends actionform {</p> <p>........</p> <p>Public string getthetext () {</p> <p>Return Thet;</p> <p>}</p> <p>Public void setthetxt (string thetext) {</p> <p>THIS.THETEXT = Thet;</p> <p>}</p> <p>Public Formfile getthefile () {</p> <p>Return thefile;</p> <p>}</p> <p>Public void setthefile (formfile thefile) {</p> <p>THIS.THEFILE = Thefile;</p> <p>}</p> <p>........</p> <p>}</p> <p>Note that formfile is built in org.apache.struts.upload in package</p> <p>(3) Write uploadAction</p> <p>Public ActionForward Execute (ActionMapping Mapping,</p> <p>Actionform Form,</p> <p>HTTPSERVLETREQUEST REQUEST,</p> <p>HttpservletResponse response) {</p> <p>UPLOADFORM Theform = (UPLOADFORM) Form;</p> <p>String text = theform.getthetext ();</p> <p>Formfile file = theform.getthefile ();</p> <p>String filename = file.getfilename ();</p> <p>String contenttype = file.getContentType ();</p> <p>String size = (file.getfilesize () "bytes");</p> <p>.... // See how you handle</p> <p>.... // You can use InputStream to get file.getinputstream, etc.</p> <p>Return mapping.findforward ("thepageyouwannago");</p> <p>}</p> <p>(4) Establish struts-config.xml</p> <p><form-beneans></p> <p><form-bean name = "Uploadform"</p> <p>TYPE = "org.apache.struts.Webapp.upload.uploadform" /></p> <p></ form-beans></p> <p><action-mappings></p> <p><! - UPLOAD ACTION -></p> <p><action path = "/ upload" type = "org.apache.struts.Webapp.upload.uploadAction" name = "UPLOADFORM" scope = "request" infut = "/ upload.jsp"></p> <p><forward name = "display" path = "/ display.jsp" /></p> <p></ action></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-52845.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="52845" 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.035</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 = 'gcmd9PXERYw8y9Te5u3kQIEoNcrS8SJM4k9Y_2FJQVl51dyNCkWNFMyg5_2BoGx2tVLKKN_2FF06g5yVegaPi7USn_2FCQ_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>