package servlet;标签:控件,1208,System,随堂,item,println,import,上传,out From: https://blog.51cto.com/u_13137233/5920436
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
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 java.io.File;
import java.io.IOException;
import java.util.List;
@WebServlet("/upload")
public class Upload extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("解决乱码问题");
req.setCharacterEncoding("utf8");
System.out.println("已进入post请求");
System.out.println("确认这个表单是不是multipart表单");
boolean multipartContent = ServletFileUpload.isMultipartContent(req);
System.out.println(multipartContent);
System.out.println("期望上传的文件都保存在一个名叫uploads目录中");
System.out.println("获取该目录的路径");
String uploadsPath = req.getServletContext().getRealPath("uploads");
System.out.println(uploadsPath);
System.out.println("判断这个路径是否存在");
File uploadFile = new File(uploadsPath);
boolean exists = uploadFile.exists();
if (!exists) {
System.out.println("文件夹不存在,我们就创建");
boolean mkdir = uploadFile.mkdir();
System.out.println("创建目录的结果");
System.out.println(mkdir);
}
System.out.println("代码来到此处,一定就存在上传资源的存放目录了");
System.out.println(uploadsPath);
System.out.println("主要的保存文件操作===========");
if (multipartContent) {
// 工厂
FileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 规则
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 利用规则解析请求
List<FileItem> list = null;
try {
list = servletFileUpload.parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
}
// 【item1,itemn】
// 遍历集合
for (FileItem item :
list) {
// 判断成员是否是普通的字段控件
boolean formField = item.isFormField();
// 如果是普通控件
if (formField) {
// 当前item是一个普通的控件
// 取值
String value = item.getString("utf8");
String name = item.getName();
System.out.println("当前控件的name是" + name);
System.out.println("当前控件的值是" + value);
}
// 如果不是普通控件
else {
// 当前item一定是文件上传控件
// 获取文件名
String name = item.getName();
// 拼一个保存的路径
File file = new File(uploadsPath, name);
// 保存数据
try {
item.write(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else {
String name = req.getParameter("name");
}
}
}