基于servlet完成文件上传功能_方式二【代码简化版】

本次文件依靠第三方组件(Apache)进行实现

commons-fileupload组件:

下载jar包:

commons-fileupload.jar

jar包下载地址:
http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi
操作指南:
http://commons.apache.org/proper/commons-fileupload/using.html

commons-io.jar

jar包下载地址:
http://commons.apache.org/proper/commons-io/download_io.cgi
操作指南:
http://commons.apache.org/proper/commons-io/description.html

文件上传的前提

1.form表单的method必须是post
2.form表单的组件得是file属性:比如:<input type="file" name="photoName" >
3.form表单的enctype必须是multipart/form-data 以二进制字节流进行提交 传统接收参数的方式无效

代码演示

1. jsp页面设计

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
  <head>
    <title>MrYang Design File Upload</title>
  </head>
  
  <body>
   	<form action="${pageContext.request.contextPath}/servlet/UploadServlet" enctype="multipart/form-data" method="post" >
   		名称<input type="text" name="name" ><br/><br/>
   		密码<input type="text" name="pwd" ><br/><br/>
   		<input type="file" name="photoName" ><br/><br/>
		<input type="submit" value="上传" >
   	</form>
  </body>
</html>

  2.servlet中进行接受并且进行上传处理

package cn.javabs.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

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.FilenameUtils;

import cn.javabs.exception.MyFileUploadException;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/**
		 * Set CharEncoding
		 */
		response.setContentType("text/html ;charset = utf-8 ");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");

		//  1. 用于判断jsp表单中的enctype 的属性值是不是multipart/form-data
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 如果不是multipart/form-data 则提醒
		if (!isMultipart) {
			response.getWriter().write("提交的不是multipart/form-data");
			return;
		}
		//实例化 磁盘文件项工厂对象  
		DiskFileItemFactory factory = new DiskFileItemFactory();

		//ServletFileUpload是用于解析request对象
		ServletFileUpload upload = new ServletFileUpload(factory);

		List<FileItem> items = null;

		try {
		//	通过ServletFileUpload得到所有上传项.每一个FileItem就相当于一个上传项
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			throw new RuntimeException(e);
		}
		System.out.println("我们来一起看一下items是:" + items);
		// 循环取出所有的组件  其中组件包含有  普通组件 和  上传组件
		for (FileItem item : items) {
		//	通过判断确定 item中的普通组件   使用的判断方法是isFormField 
			// 是普通的表单字段
			if(item.isFormField()){
				System.out.println("这是普通的表单字段");
				// 获取表单中的属性  
				String fieldName = item.getFieldName();
				// 获取表单中的属性所对应的值  
				String fieldValue = item.getString();
				
				System.out.println(fieldName +":" + fieldValue);
			}	
			// 是上传的表单字段
			else{
				System.out.println("这是上传的表单字段");
				
				// 获取上传文件的名称
				String uploadName = item.getName();
				
				// 判断上传文件的名称是否为null,如果不为空
				if(uploadName != null){
					// 文件名称     =		 获取文件名称,并且包含后缀
					uploadName = FilenameUtils.getName(uploadName);
				}
				
				// 文件存放的真实路径	 其实files文件夹 存放在Tomcat服务器的项目里面
				String filePath = getServletContext().getRealPath("/files");
				
				// 根据真实的路径 进行实例化创建目录
				File file = new File(filePath);
				
				// 如果目录不存在
				if(!file.exists()){
					//创建多级目录
					file.mkdirs();
				}
				// 根据  真实目录  + "\" + 文件名称  [file.separator 的结果是 "\"]
				try {
					item.write(new File(filePath +  file.separator + uploadName));
				} catch (Exception e) {
					throw new MyFileUploadException(e);
				}
			}
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);

	}

}
  3.其中涉及到一个自定义的异常 
package cn.javabs.exception;

public class MyFileUploadException extends RuntimeException {

	public MyFileUploadException() {
		
	}

	public MyFileUploadException(String message) {
		super(message);
		
	}

	public MyFileUploadException(Throwable cause) {
		super(cause);
		
	}

	public MyFileUploadException(String message, Throwable cause) {
		super(message, cause);
		
	}

	public MyFileUploadException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		
	}

}

  

  4别忘了还有web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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_3_0.xsd">
  <display-name></display-name>
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>cn.javabs.web.controller.UploadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/servlet/UploadServlet</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  

 

posted @ 2019-04-04 00:50  杨校  阅读(491)  评论(0编辑  收藏  举报