Implement file upload using FileUpload components

xiaoxiao2021-03-06  127

File uploads are very common in web applications. It is very easy to implement file upload features in the servlet / jsp environment. JSP application adds a file upload function. The Common-FileUpload component is one of the open source projects of Apache, which can be downloaded from http://jakarta.apache.org/commons/fileupload/. This component is simple and easy to use, upload one or more files at a time, and can limit the file size. After downloading the zip package, copy the commons-fileupload-1.0.jar to Tomcat's WebApps / Your WebApp / Web-INF / LIB / Under, if the directory does not exist, please ask your own directory. New Servlet: Upload.java is used for file upload: import java.io. *; Import java.util. *; Import javax.servlet. *; Import javax.servlet.http. *; Import org.apache.commons.fileupload PUBLIC CLASS UPLOAD EXTENDS HTTPSERVLET {Private String UploadPath = "C: // UPLOAD / /"; // Directory for the storage of uploaded files prince Temppath = "c: // upload //TMP //"; // / Directory (HTTPSERVLETREQUEST, HTTPSERVLETREQUEST REQUEST, HTTPSERVLETREQUEST, HTTPSERVLETREQUEST, HTTPSERVLETREQUEST REESPONSE) THROWS IOEXCETEXCEPTION}} The file upload is implemented in the dopost () method after the servlet receives the POST request sent by the browser.

The following sample code: public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {try {DiskFileUpload fu = new DiskFileUpload (); // set the maximum file size, this is 4MB fu.setSizeMax (4194304); // Set Buffer size, here is 4kb Fu.setSizetHold (4096); // Settings Temporary Directory: Fu.SetRepositoryPath (Temppath); // Get all files: List fileItems = fu.parsequest; itemic i = fileItems.ITerator (); // handle each file in turn: while (I.hasNext ()) {fileItem Fi = (fileItem) i.next (); // Get file name, this file name includes path: string filename = fi.getname (); If (filename! = Null) {// You can record user and file information // ... // write file a.txt, you can also extract file name from FileName: FI.WRITE (New File (UploadPath A.TXT "));}} // Jump to Upload Success Tips Page} Catch (Exception E) {// You can jump out of the wrong page}} If you want to read the specified upload in the configuration file Folder, you can execute in the init () method: public void init () throws servletex CEPTION {UPLOADPATH = .... Temppath = .... // Folder does not exist automatically: if (! new file (uploadPath) .Indirectory ()) new file (UploadPath) .mkdirs (); if (! New file ()) .MKDIRECTORY ()) .MKDIRS ();} Compiles the servlet, pay attention to specify the classpath to ensure that contains the commons-upload-1.0.jar and Tomcat / Common / lib / servlet-API. JAR. Configure the servlet, open Tomcat / WebApps / Your webapp / web, INF / Web.xml with Notepad, and create a new one.

转载请注明原文地址:https://www.9cbs.com/read-97338.html

New Post(0)