导包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
前端
<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
用户名: <input type="text" name="username"><br>
<input type="file" name="file1"><br>
<input type="file" name="file2"><br>
<input type="submit" value="提交"> | <input type="reset" value="重置">
注意这里的enctype="multipart/form-data"一定要写(加密类型),还有请求方式要为POST
servlet
package com.Google.FileUp;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
public class FileupServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//1,判断前端传过来的表单是普通表单还是文件表单
if (!ServletFileUpload.isMultipartContent(req)) {
return;//这里表达的是,如果是普通表单直接返回
}
/*2,通过了if,就表明是文件表单,给文件表单创建个目录,
建议放在WEB-INF目录下,这样用户不能访问*/
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {//如果文件夹不存在
uploadFile.mkdir();//就创建一个目录
}
/*
* 3,缓存,临时文件
* 临时目录,如果文件超过了预期的大小,我们就把他放进临时目录中,过几天会自动清除,或者提醒用户存为永久
* */
//创建缓存目录
String temPath = this.getServletContext().getRealPath("/WEB-INF/tem");
File temFlie = new File(temPath);
if (!temFlie.exists()) {
temFlie.mkdir();
}
//处理上传文件
//1.创建DiskFileItemfactory对象,设置文件上传路径和文件大小
DiskFileItemFactory factory = new DiskFileItemFactory();
//通过设置临界点(Threshold),当上传文件大于这个临界点时,会把文件放到缓冲区目录中
factory.setSizeThreshold(1024 * 1024);
//设置临时文件的缓冲目录
factory.setRepository(temFlie);
//2.创建ServletfileupLoad对象
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//监听文件上传进度
fileUpload.getProgressListener(/*new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int pIteams) {
System.out.println("总大小:" + pContentLength + "已上传:" + pBytesRead);
}
}*/);
//处理乱码问题
fileUpload.setHeaderEncoding("UTF-8");
//设置单个文件的最大值
fileUpload.setFileSizeMax(1024 * 1024 * 10);
//设置总共能上传文件的最大值
fileUpload.setSizeMax(1024 * 1024 * 10);
//处理上传文件
//把前端请求解析,封装成一个Fileiteam对象
List<FileItem> fileItems = fileUpload.parseRequest(req);
for (FileItem fileItem : fileItems) {
//判断上传的表单是普通表单还是文件表单
if(fileItem.isFormField()){//判断是普通表单
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name+value);
}else{//文件的情况
//=========处理文件===============//
//拿到上传文件的名字
String upLoadName = fileItem.getFieldName();
System.out.println("fileName:"+upLoadName);
//可能存在文件不合法的情况
if(upLoadName.trim().equals("")||upLoadName==null){//trim()返回本身的字符串
continue;//如果不合法,继续下面的程序
}
//获得文件的上传名
String fileName = upLoadName.substring(upLoadName.lastIndexOf("/") + 1);
//获得文件的后缀名
String fileExtName = upLoadName.substring(upLoadName.lastIndexOf(".") + 1);
/*
如果,文件后缀名不是我想要的,直接return 告诉作者,文件类型有误
*/
//使用UUID保证文件名唯一
String uuidPath = UUID.randomUUID().toString();
//=========存放地址===============//
String realPath = uploadPath+"/"+uuidPath;
File realPathFile = new File(realPath);
//给每个文件创建一个文件夹
if(!realPathFile.exists()){
realPathFile.mkdir();
}
//======上传文件====//
InputStream inputStream = fileItem.getInputStream();
//创建一个文件输出流,也就是文件最后到达的地方
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
//创建一个缓冲区
byte[] buffer = new byte[1024 * 1024];
//判断是否读取完璧
int i =0;
while((i=inputStream.read(buffer))>0){
fos.write(buffer,0,i);
}
fos.close();
inputStream.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}