(1)准备好前台页面 Upload.html 表单action =上传文件后台接口 method=“post“ enctype=”multipart/form-data“ 文件输入框<input type=”file”>
<title>文件上传演示</title>
</head>
<body>
<FORM action="/upload" method="post" enctype="multipart/form-data">
<input type="file"name="files">
<input type="file">
<input type="submit" value="上传">
</FORM>
</body>
</html>
(2)加入相应的jar包 commons-fileupload-1.3.2、commons-io-2.5.jar (3)准备接受文件上传servlet url路径一定要与上面表单的action一致
@WebServlet(urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
(4)把代码写到doPost下
try {
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = item.getName();
//定义上传文件的存放路径
String path = request.getServletContext().getRealPath("/uploadFiles");
//定义上传文件的完整路径
String filePath = String.format("%s/%s",path,fileName);
File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
System.out.println(filePath);
// 保存文件到硬盘
item.write(storeFile);
}
}
} catch (Exception ex) {
}
}
(5)在web下创建一个uploadFiles目录存放上传内容 注意:空目录idea不会更新到服务器(这应该是一个bug),所以可以在里面随便放个文件,哪怕再删除掉也行,迫使idea更新 jar包地址 链接:https://pan.baidu.com/s/1q85ET5-TzFEK5bZALMQM0A 密码:f7ga
|