Javaweb使用getPart来接收表单文件
使用getPart接收表单文件时,注意Tomcat版本要在8之上。
前台 : form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/test" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
</body>
</html>后台:TestServlet
@WebServlet(name = "TestServlet", urlPatterns = "/test")
@MultipartConfig
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取文件,参数为前台的name
Part part = request.getPart("file");
//获取文件名,获取到文件名的格式如:a.jpg
String fileName = part.getSubmittedFileName();
/**
截取文件名的后缀名:
photo.lastIndexOf(‘.‘)的返回值为"."的位置,加1表示后缀名的起始位置。
photo.substring(photo.lastIndexOf(‘.‘)+1),表示从后缀名的起始位置截取到结束位置。
* */
String fileType = fileName.substring(fileName.lastIndexOf(‘.‘) + 1);
//判断该文件是不是图片格式
if (!("jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType))) {
//不是图片格式,停止下一步,并将信息反馈给前台页面
request.setAttribute("msg","上传的文件必须为图片");
request.getRequestDispatcher(request.getContextPath() + "/form.jsp").forward(request, response);
return;
}
//是图片类型,构建一个上传图片的存储路径
String path = "E:\\upload";
File file = new File(path);
if (!file.exists()) {
file.mkdirs(); //创建文件和文件夹
}
//将part内容写到文件夹内,生成一个文件
part.write(path + "/" + fileName);
}
}String path = "E:\\testPic";设置成本地文件夹路径与Tomcat服务器脱离关联,可以防止文件丢失。但需要将该文件夹挂载到Tomcat服务器。
挂载方式:
Eclipse:
1、双击集成在Eclipse中的tomcat服务器

2、点击添加额外的web资源

3、将本地存储上传文件的文件夹添加进来即可!

一定要ctrl + S
IDEA:


相关推荐
learningever 2020-09-19
nercon 2020-07-26
haohong 2020-07-18
dadaooxx 2020-07-04
行吟阁 2020-06-26
dadaooxx 2020-06-13
qsdnet我想学编程 2020-06-09
pythonclass 2020-06-07
pythonclass 2020-06-04
lyg0 2020-06-04
WebVincent 2020-06-03
niehanmin 2020-05-28
pythonclass 2020-05-09
gufudhn 2020-04-30
行吟阁 2020-04-18
swiftwwj 2020-03-08
nercon 2020-03-03
玫瑰小妖 2020-02-24