📜  Servlet-文件上传

📅  最后修改于: 2020-11-12 05:42:59             🧑  作者: Mango


Servlet可以与HTML表单标签一起使用,以允许用户将文件上传到服务器。上传的文件可以是文本文件或图像文件,也可以是任何文档。

创建文件上传表单

下面的以下HTM代码创建一个上载器表单。以下是要注意的重点-

  • 表单方法属性应设置为POST方法,并且不能使用GET方法

  • 表单enctype属性应设置为multipart / form-data

  • 表单操作属性应设置为Servlet文件,该文件将处理后端服务器上的文件上传。以下示例是使用UploadServlet servlet上载文件。

  • 要上传单个文件,您应该使用属性类型为“ file”的单个标记。要允许上传多个文件,请包含多个输入标签,这些输入标签的name属性值不同。浏览器将“浏览”按钮与每个按钮相关联。

File Uploading Form
   
   
   
      

File Upload:

Select a file to upload:

这将显示以下结果,该结果将允许从本地PC选择文件,并且当用户单击“上传文件”时,表单将与所选fil一起提交-

File Upload: 
Select a file to upload:  
 
 
 
 
NOTE: This is just dummy form and would not work.

编写后端Servlet

以下是Servlet UploadServlet ,它将负责接受上载的文件并将其存储在目录 / webapps / data中。也可以使用外部配置(例如web.xml中的context-param元素)添加此目录名称,如下所示-


   ....
    
      Location to store uploaded file 
      file-upload 
      
         c:\apache-tomcat-5.5.29\webapps\data\
       
   
   ....

以下是UploadServlet的源代码,它可以一次处理多个文件的上载。在继续之前,请确保以下内容-

  • 以下示例取决于FileUpload,因此请确保您在类路径中具有commons-fileupload.xxjar文件的最新版本。您可以从https://commons.apache.org/fileupload/下载。

  • FileUpload取决于Commons IO,因此请确保您在类路径中具有commons-io-xxjar文件的最新版本。您可以从https://commons.apache.org/io/下载。

  • 在测试以下示例时,应上传大小小于maxFileSize的文件,否则将不会上传文件。

  • 确保您已经预先创建了目录c:\ temp和c:\ apache-tomcat8.0.28 \ webapps \ data。

// Import required java libraries
import java.io.*;
import java.util.*;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {
   
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath = getServletContext().getInitParameter("file-upload"); 
   }
   
   public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
   
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
   
      if( !isMultipart ) {
         out.println("");
         out.println("");
         out.println("Servlet upload");  
         out.println("");
         out.println("");
         out.println("

No file uploaded

"); out.println(""); out.println(""); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println(""); out.println(""); out.println("Servlet upload"); out.println(""); out.println(""); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf("\\") >= 0 ) { file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ; } fi.write( file ) ; out.println("Uploaded Filename: " + fileName + "
"); } } out.println(""); out.println(""); } catch(Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required."); } } }

编译并运行Servlet

编译上面的Servlet UploadServlet并在web.xml文件中创建所需的条目,如下所示。


   UploadServlet
   UploadServlet



   UploadServlet
   /UploadServlet

现在,尝试使用上面创建的HTML表单上传文件。当您尝试http:// localhost:8080 / UploadFile.htm时,它将显示以下结果,这将帮助您从本地计算机上载任何文件。

File Upload: 
Select a file to upload:
 
 

如果您的Servlet脚本运行良好,则应将文件上传到c:\ apache-tomcat8.0.28 \ webapps \ data \目录中。