写一个servlet,处理包含学号和姓名以及头像文件(图像)的表单,将头像存储到服务器upload目录下面以学号-姓名命名的文件夹下面,文件名为avatar,保持扩展名不变。
时间: 2024-10-21 16:10:40 浏览: 32
创建一个Servlet来处理这种表单提交通常涉及以下步骤:
首先,确保你已经导入了必要的Java Servlet API包,并且已经配置了一个Servlet容器(如Tomcat)。下面是一个简单的Servlet示例,它实现了`doPost`方法来处理HTTP POST请求:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
public class AvatarUploaderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取表单数据
String studentId = request.getParameter("student_id");
String name = request.getParameter("name");
String avatarFile = request.getParameter("avatar");
// 检查是否收到头像文件
if (avatarFile == null || avatarFile.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No image file received.");
return;
}
// 创建上传目录路径
String uploadDir = "upload/" + studentId + "-" + name + "/";
File dir = new File(uploadDir);
if (!dir.exists() && !dir.mkdirs()) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create directory.");
return;
}
// 获取图片流并保存到服务器
InputStream inputStream = request.getInputStream();
String fileName = studentId + "-" + name + "-avatar." + getFileNameExtension(avatarFile); // 保留原始扩展名
File outputFile = new File(dir, fileName);
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
} finally {
inputStream.close(); // 关闭输入流
}
response.setContentType("text/html");
response.getWriter().println("Image uploaded successfully. Filename: " + fileName);
}
private String getFileNameExtension(String filenameWithoutExt) {
int lastDot = filenameWithoutExt.lastIndexOf('.');
return lastDot == -1 ? "" : filenameWithoutExt.substring(lastDot);
}
}
阅读全文