JavaWeb实现文件上传
- 首先配置文件上传的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<%--
method 必须是post get无法获得大数据的文件
enctype="multipart/form-data" 表示表单中存在上传数据
--%>
<form action="${pageContext.request.contextPath}/file" enctype="multipart/form-data" method="post">
<p>上传用户:<input type="text" name="userName"></p>
<p>选择文件:<input type="file" name="uploadFile"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
- 配置index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/fileup.jsp">上传文件</a>
</body>
</html>
- 配置文件上传的servlet
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 javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;
public class UpLoadServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request, response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//判断上传的文件是普通的文本表单还是文件表单
//如果是文件表单则返回true,这里取反,说明是普通表单
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
//如果if为false,则说明我们的表单是带文件上传的
//创建一个上传文件的保存路径 建议在WEB-INF路径下 安全,用户无法直接访问上传的文件
String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File file1 = new File(uploadPath);
if (!file1.exists()){
file1.mkdir();
}
//加入文件超过预期大小,我们把它放到一个临时文件中,过几天自动删除 或者提示用户保存永久
String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
File file2 = new File(tmpPath);
if (!file2.exists()) {
file2.mkdir();
}
//处理上传的文件,通过工厂来获取
DiskFileItemFactory factory = getDiskFileItemFactory(file2);
//获取ServletFileUpload对象 文件上传解析器
ServletFileUpload upload = getServletFileUpload(factory);
//把前端请求解析,封装成一个FileItem对象
try {
//获得文件上传是否成功的消息
String msg = getMSG(uploadPath,upload,request);
request.setAttribute("msg",msg);
request.getRequestDispatcher("info.jsp").forward(request,response);
} catch (FileUploadException e) {
e.printStackTrace();
}
}
public DiskFileItemFactory getDiskFileItemFactory(File file) {
//处理上传的文件
//1. 创建一个DiskFileItemFactory对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//2.设置缓冲区,当上传的文件大于缓冲区时,放到临时文件中
factory.setSizeThreshold(1024 * 1024);//1MB
//3.设置临时目录的保存文件
factory.setRepository(file);
return factory;
}
public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
upload.setProgressListener((long l, long l1, int i)-> {
System.out.println("总大小:" + l1 + "已上传" + l);
}
);
//设置文件编码格式,防止乱码
upload.setHeaderEncoding("utf-8");
//设置单个文件的最大值
upload.setFileSizeMax(1024 * 1024);//1MB
//设置总共能上传文件的大小
upload.setSizeMax(1024 * 1024 * 10);//10MB
return upload;
}
public String getMSG(String uploadPath, ServletFileUpload upload, HttpServletRequest request) throws IOException, FileUploadException {
String msg = "";
List<FileItem> list = upload.parseRequest(request);
for (FileItem fileItem : list) {
//判断是文件还是表单
if (fileItem.isFormField()) {
//获得上传文件的用户名字 getFieldName指的是前端表单控件的name
String name = fileItem.getFieldName();
//将上传文件用户的名字的编码格式改为utf-8,防止乱码
String value = fileItem.getString("utf-8");
System.out.println(name + ":" + value);
} else {
//拿到文件名
String fileName = fileItem.getName();
System.out.println("上传的文件名:" + fileName);
if (fileName.trim().equals("") || fileName == null) {
msg = "文件不存在,无法保存";
return msg;//文件不存在 无法保存
}
//获得文件名 web/resources/1.png
String name = fileName.substring(fileName.lastIndexOf("/") + 1);
//获得文件后缀
String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
System.out.println("文件名:" + name + "文件类型" + fileExtName);
//防止图片名字重复 UUID(唯一识别的)
String uuidFileName = UUID.randomUUID().toString() + "_" + name;
//文件真实存在的路径
String realPath = uploadPath + "/" + uuidFileName;
//给路径创建一个文件夹
File realPathFile = new File(realPath);
if (!realPathFile.exists()) {
realPathFile.mkdir();
}
//[================================================
//获得文件上传的流
InputStream inputStream = fileItem.getInputStream();
//用流写入文件中
FileOutputStream fos = new FileOutputStream(realPath+"/"+name);
byte[] b = new byte[1024];
int len = 0;
while ((len = inputStream.read(b)) != -1) {
fos.write(b, 0, len);
}
msg = "文件上传成功!";
//关闭流
fos.close();
inputStream.close();
}
}
return msg;
}
}
- 配置上传成功的jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传成功</title>
</head>
<body>
<h1>
${msg}
</h1>
</body>
</html>
- 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>UpLoadServlet</servlet-name>
<servlet-class>com.baidu.servlet.UpLoadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpLoadServlet</servlet-name>
<url-pattern>/file</url-pattern>
</servlet-mapping>
</web-app>
用tomcat把项目跑一遍,再查看out路径下,就会有你上传的文件