【Java.Web】Servlet —— 实例 之 上传文件


上传文件

上传文件是指把客户端的文件发送到服务器端。当客户端向服务器上传文件时,客户端发送的http请求正文采用multipart/form-data数据类型。

不管http请求正文为何种设局类型,Servlet容器都会把http请求包装成一个HttpServletRequest对象。

为了简化“multipart/form-data”数据类型的处理,可以利用apache commons fileupload工具包来处理,具体参见:Java.ThirdParty.Apache Commons File Upload


创建一个名为:uploadfile.html的文件,定义一个用于上传文件的复合表单,表单的action为对应servlet的url-pattern

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Files</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data" action="uploadfile">
    	File Upload Testing:<br/>
    	Upload File 1: <input type="file" name="file1" size="30"/><br/>
    	Upload File 2: <input type="file" name="file2" size="30"/><br/>
    	<input type="submit" name="submit" value="Upload"/>
    	<input type="reset" name="reset" value="Reset"/>
    </form>	
</body>
</html>

在浏览器中访问:

http://localhost:8080/base-webapp/uploadfile.html


页面如下:



浏览器生成的http request如下:



创建一个Servlet用于处理提交的表单:

package com.gof.test.servlet;

import java.util.List;
import java.util.Iterator;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileCleaningTracker;

public class UploadFileServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3396770132755929933L;
	private String filePath = null;
	private String tempFilePath = null;
	
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
        // get the property in servlet configuration in web.xml 
        filePath = getInitParameter("filePath");
        tempFilePath = getInitParameter("tempFilePath");
        // get the real path is disk
        filePath = getServletContext().getRealPath(filePath);
        tempFilePath = getServletContext().getRealPath(tempFilePath);
    }

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException{
    	PrintWriter out = resp.getWriter();
    	// For Chinese File Name
    	req.setCharacterEncoding("utf-8");
    	
		// Begin to parse the uploaded files
		try{
		    DiskFileItemFactory factory = new DiskFileItemFactory();
		    // Set the factory constraints
		    // Set the buffer size for file upload when write to disk
		    factory.setSizeThreshold(4 * 1024);
		    // Set the temporary path
		    factory.setRepository(new File(tempFilePath));
		    
		    
		
		    // Create a new file upload handler
		    ServletFileUpload upload = new ServletFileUpload(factory);
		    // Set overall request size constraint
		    upload.setFileSizeMax(4 * 1024 * 1024);
		
		    // Parse the request
		    List<FileItem> items = upload.parseRequest(req);
		    // Process the uploaded items
		    Iterator<FileItem> iter = items.iterator();
		    while (iter.hasNext()){
		    	FileItem item = iter.next();
		    	
		    	if (item.isFormField()){
		    		processFormFields(item, out);
		    	}else{
		    		processUploadFiles(item, out);
		    	}
		    }
		    
		    out.close();
		}catch (Exception e){
			e.printStackTrace();
		}
		
    }
	
	private void processFormFields(FileItem item, PrintWriter out){
		String name = item.getFieldName();
		String value = item.getString();
		
		out.println("The file name is " + name + "; The value is " + value);
	}
	
	private void processUploadFiles(FileItem item, PrintWriter out) throws Exception{
		String fieldName = item.getFieldName();
		String fileName = item.getName();
		String contentType = item.getContentType();
		long sizeInBytes = item.getSize();
		
		if ((fileName == null) || (sizeInBytes == 0)){
			return;
		}
		
		// write the file to disk
		
		File uploadedFile = new File(filePath + "/" + fileName);
		item.write(uploadedFile);
		
		out.println("The file " + fileName + " is saved; The size of the file is " + sizeInBytes + " bytes");
	}
}

在web.xml中注册上面的servlet,并配置保存文件的参数和临时目录:/upload, /tempupload:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
  <display-name>Base Java Webapp</display-name>
  <description>A Basic Maven Java Webapp Application</description>
  
  <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  
  <!-- test url: http://localhost:8080/base-webapp/download?filename=testreport.txt -->
  <servlet>
  	<servlet-name>downloadtest</servlet-name>
  	<servlet-class>com.gof.test.servlet.DownloadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>downloadtest</servlet-name>
      <url-pattern>/download</url-pattern>
  </servlet-mapping>
  
  <!-- test upload file: http://localhost:8080/base-webapp/uploadfile.html -->
  <servlet>
  	<servlet-name>uploadfiletest</servlet-name>
  	<servlet-class>com.gof.test.servlet.UploadFileServlet</servlet-class>
  	<init-param>
  	    <param-name>filePath</param-name>
  	    <param-value>/upload</param-value>
  	</init-param>
  	<init-param>
  	    <param-name>tempFilePath</param-name>
  	    <param-value>/tempupload</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>uploadfiletest</servlet-name>
      <url-pattern>/uploadfile</url-pattern>
  </servlet-mapping>
  
</web-app>

在webapp的根目录(base-webapp)下,创建上面的两个目录:



在页面中选择文件并点击upload,浏览器将请求名为uploadfile的Servlet,在webapp的目录upload下,可以找到上传的文件:



该Servlet同时向客户端返回如下的页面:

http://localhost:8080/base-webapp/uploadfile






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值