Servlet 实现文件上传

使用Servlet原生API进行文件上传:

一、Upload.java(文件上传Servlet)

package servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import exception.UploadException;
import util.FileUtil;
/**
 * 文件上传Servlet
 * @author GengYB
 *
 */
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//判断是不是MultipartContent
		boolean isMC = ServletFileUpload.isMultipartContent(req);
		if(!isMC) 
			throw new UploadException("<form> no set \"method='post'\" or no set enctype='multipart/form-data' attribute!");
		Collection<Part> parts = req.getParts();//文件都被包装在这里
		for (Part part : parts) {
			String contentType = part.getContentType();//获取文件类型
			System.out.println(contentType);
			String name = part.getName(); //获取表单域name属性值
			System.out.println(name);
			String submittedFileName = part.getSubmittedFileName();//获取文件名
			System.out.println(submittedFileName);
			long size = part.getSize(); //获取文件大小
			System.out.println(size);
			InputStream inputStream = part.getInputStream();//获取输入流(文件内容就是从这里读取)
			System.out.println("-----------------");
			if(contentType!=null) {//文件part
				//处理文件
				//将文件保存在D:\\save目录下
				FileUtil.copyFile(inputStream, "D:\\save", submittedFileName);
			}else {//文本域
				//处理普通input域
				//自己去摸索吧
			}
		}
	}
}

      UploadException.java( 自定义异常)

public class UploadException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	
	public UploadException() {
		super();
	}

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

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

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

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

二、FileUtil.java (文件复制工具类)

package util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author GengYB
 * 文件复制工具类
 *
 */
public final class FileUtil {
	/**
	 * 从输入流复制数据到指定文件
	 * @param is 输入流
	 * @param savePath 保存路径
	 * @param saveFileName 保存的文件名
	 */
	public static void copyFile(InputStream is,String savePath,String saveFileName) {
		File sPath = new File(savePath);
		if(!sPath.exists()) {
			sPath.mkdirs();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(savePath+File.separator+saveFileName);
			copyFile(is, fos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @param is 输入流
	 * @param os 输出流
	 */
	public static void copyFile(InputStream is, OutputStream os){
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] b = new byte[512];
		int n;
		try {
			while((n = bis.read(b)) != -1) {
				os.write(b,0,n);
			}
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				os.close();
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
三、web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>upload</servlet-name>
		<servlet-class>servlet.Upload</servlet-class>
		<multipart-config> <!-- 这个必须配置,否则报异常! -->
			<max-file-size>52428800</max-file-size>
			<max-request-size>52428800</max-request-size>
			<file-size-threshold>0</file-size-threshold>
		</multipart-config>
	</servlet>
	<servlet-mapping>
		<servlet-name>upload</servlet-name>
		<url-pattern>/upload</url-pattern>
	</servlet-mapping>
</web-app>

     注意:

<multipart-config> <!-- 这个必须配置,否则报异常! -->

四、index.jsp(前端页面)
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Home</title>
</head>
<body>
	<form action="upload" method="post" enctype="multipart/form-data">
		<input type="file" name="file1" multiple="multiple"/>
		<input type="text" name="text1" />
		<input type="submit" value="提交" />
	</form>
</body>
</html>
     这里说一下,form的method属性必须设置为post,另外必须设置enctype="multipart/form-data".

五、演示

     选择文件,支持多文件得意,点击提交。

     查看D:\save

      

相关文章
相关标签/搜索