1. 程式人生 > >Servlet 實現檔案上傳

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