使用Servlet上传文件
下面的案例中,我们将学习如何将文件上传到服务器。要将文件上传到服务器,表单方法必须使用Post方式提交,而enctype类型必须改为multipart/form-data
。
1 编写上传页面
upload.jsp用于选择上传文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一点教程网-使用Servlet上传文件</title>
</head>
<body>
<h1>使用Servlet上传文件</h1>
<form action="Upload" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" name="fname"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
2 编写UploadServlet
UploadServlet用于完成核心的上传文件逻辑:
import com.oreilly.servlet.MultipartRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 一点教程网 - http://www.yiidian.com
*/
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
MultipartRequest m=new MultipartRequest(request,"d:/upload");
out.print("上传成功");
}
}
这里有两个注意点:
- 必须在对应目录创建目录,例如上面示例需要在D盘创建upload目录
- 必须在项目导入cos.jar文件上传组件包,点击这里下载
3 配置web.xml
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_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/Upload</url-pattern>
</servlet-mapping>
</web-app>
4 运行测试
检查upload目录是否有上传的文件:
热门文章
优秀文章