多文件上传

1. 项目结构


2.1 UploadServlet

package com;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url="upload.jsp";
		// 1 设置post编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 2 判断是不是多文件上传
		boolean isMultipart=ServletFileUpload.isMultipartContent(request);
		if(!isMultipart) {
			response.getWriter().write("传输方式有错误!");
			return;
		}
		//3 在servlet中规定上传文件,单个大小不能超过4m,总共大小不能超过6m;
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setFileSizeMax(4*1024*1024);//单个大小不能超过4m
		upload.setSizeMax(6*1024*1024);//总共大小不能超过6m
		
		// 获取upload实际路径
		String storePath=request.getServletContext().getRealPath("/upload");
		System.out.println(storePath);
		// 4 获取多文件上传Item
		try {
			List<FileItem> fileItems = upload.parseRequest(request);
			for(FileItem item:fileItems) {
				if(!item.isFormField()) {
					//5在servlet中判断,上传格式必须是“素材”中的上传文件格式,mine类型在《mine类型.txt》中;(考试素材见:桌面/考试素材/第五题素材文件夹)
					String contentType = item.getContentType();
					if(contentType!=null && contentType.startsWith("image")) {
						// 文件上传:流的读写
						InputStream is = item.getInputStream();
						// 获取文件名字
						String fileName = item.getName();
						System.out.println(fileName);
						if (fileName == null || "".equals(fileName.trim())) {
							continue;
						}
						// 截取文件名字:---a.jpg
//						fileName.substring(fileName.lastIndexOf("\\") + 1);
						String path=makeStorePath(storePath)+"\\"+fileName;;
						FileOutputStream fos=new FileOutputStream(path);
						byte[] buffer=new byte[1024*8];
						int len=-1;
						while((len=is.read(buffer))!=-1) {
							fos.write(buffer, 0, len);
						}
						// 设置文件名字
						request.setAttribute(item.getFieldName(), fileName);
						// 释放资源
						is.close();
						fos.close();
						item.delete();
						url="uploadSuccess.jsp";
					}
				} else {
					request.setAttribute("msg", "上传文件格式有错误!");
				}
				
			}
		} catch (FileUploadException e) {
			request.setAttribute("msg", "文件上传失败");
		} 
		
		request.getRequestDispatcher(url).forward(request, response);
	}

	private String makeStorePath(String storePath) {
		Date date=new Date();
		DateFormat format=DateFormat.getDateInstance(DateFormat.MEDIUM);
		String s=format.format(date);
		String path=storePath+"\\"+s;
		// 假如这个文件夹不存在,就创建一个文件夹
		File file=new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		return path;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
2.2 upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	文件上传:
	<form action="${pageContext.request.contextPath}/UploadServlet " method="post" enctype="multipart/form-data">
		<input type="file" name="file1"/><br/>
		<input type="file" name="file2"/><br/>
		<input type="submit" value="文件上传"/>
	</form>
</body>
</html>
2.3  uploadSuccess.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf">
<title>Insert title here</title>
</head>
<body>
	文件:${file1}| ${file2}上传成功
	<br />
</body>
</html>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值