Servlet程序代码如下:
package com.example;
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;
/**
* 最关键的一步就是加此注解, 否则req.getParameter("username")就获取不到任何数据
*/
@MultipartConfig //如果是文件上传,必须加此注解
public class Upload extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码格式
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("username");
System.out.println("username:" + name);
//获取part对象
Part part = req.getPart("photo");
System.out.println(part);
//通过Part对象得到上传的文件名
String filename = part.getSubmittedFileName();
System.out.println("上传的文件名:" + filename);
//得到文件存放的路径
String filepath = req.getServletContext().getRealPath("/");
System.out.println("文件存放的路径:" + filepath);
//上传文件到指定目录
part.write(filepath + "/" + filename);
System.out.println(filepath + "/" + filename);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
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"
metadata-complete="false"
version="4.0">
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.example.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>
前端jsp页面如下:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2023/2/15
Time: 17:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%-- <base href="http://localhost:8080/servlet_2023/">--%>
</head>
<body>
<form action="http://localhost:8080/servlet_2023/upload" method="post" enctype="multipart/form-data">
用户名: <input type="text" name="username"><br/>
头像: <input type="file" name="photo"><br/>
<input type="submit" value="上传">
</form>
</body>
</html>