写在前面:
先上效果图:程序运行后浏览器输入链接
http://localhost:8099/uploadWeb_war_exploded/upload.jsp
其中 8099 为自设置的端口号,uploadWeb为项目名称
界面如下图
输入用户名,并且选择相应的文件,点击提交后。系统会将相应文件下载到相应的目录下,具体的目录如下(我这里面提交的是111.png文件):
分界线
1.创建web项目,参照之前的笔记
https://www.jianshu.com/p/e79d57f303bd
2.添加外部包:
commons-io-2.10.0.jar
commons-fileupload-1.4.jar
(百度名字即可找到相关官方下载)
添加方式参考另一篇笔记
https://www.jianshu.com/p/6075847e69e5
3.主要代码文件见下图,已用红色横线标出
4.源代码参考:
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>action.uploadservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadservlet</servlet-name>
<url-pattern>/uploadservlet</url-pattern>
</servlet-mapping>
</web-app>
upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form action = "uploadservlet" enctype="multipart/form-data" method="post">
用户名:<input type="text" name="name"> <br>
密码:<input type="file" name="uploadfile"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
uploadservlet:
package action;
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.ServletException;
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;
public class uploadservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
resp.setContentType("text/html;charset=utf-8"); //解决输出中文乱码的问题
try{
//1、创建工厂类DsikFileItemFactory对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//2、使用工厂创建解析器对象
ServletFileUpload upload = new ServletFileUpload(factory);
if(!ServletFileUpload.isMultipartContent(req)){ //判断req的编码方式是否为multipart/form-data
return;
}
//3、使用解析器解析request对象
List<FileItem> list = upload.parseRequest(req);
for(FileItem item:list){
if(!item.isFormField()){//如果不是普通表单项,说明就是文件字段
String filename = item.getName(); //获取上传文件的名称
if(filename==null || filename.trim().equals("")){
continue;
}
File file = new File(this.getServletContext().getRealPath("/upload")+ "/" + filename);
item.write(file);
resp.getWriter().println("上传文件名:"+ filename);
resp.getWriter().println("上传文件类型:" + item.getContentType());
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}