前端页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<input type="file" name="image">
<br/>
<input type="submit" value="上传图片">
</form>
</body>
</html>
java代码
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
@MultipartConfig
public class ServletDemo10 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//收到图片,直接把图片保存到路径 d:/javaResource
//提前准备目录
String basePath = "d:/javaResource/images/";
Part image = req.getPart("image");
//获取想要上传的文件名
String path = basePath + image.getSubmittedFileName();
image.write(path);//图片想要保存的路径
resp.setContentType("text/html; charset = utf-8");
resp.getWriter().write("图片上传成功!");
}
}
配置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"
metadata-complete="true">
<servlet>
<servlet-name>ServletDemo10</servlet-name>
<servlet-class>ServletDemo.ServletDemo10</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo10</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
打包运行
捕捉信息
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/152939.html