一.Part类 – 上传文件
一、核心方法
1.1 HttpServletRequest 类方法
1.2 Part 类方法
二、代码示例
前端搭配 form 表单:form input type= “file”,允许通过浏览器选中一个文件上传给服务器。
Servlet 就支持处理这种上传文件的请求,把这个请求到的文件在后端获取到 ~
把服务器返回的响应的 content-type 设置成一些类型,就可以让浏览器自动触发下载 (例如 zip…)
一、核心方法
1.1 HttpServletRequest 类方法
方法 | 描述 |
---|---|
Part getPart(String name) | 获取请求中给定 name 的文件 |
Collection getParts() | 获取所有的文件 |
1.2 Part 类方法
方法 | 描述 |
---|---|
String getSubmittedFileName() | 获取提交的文件名 |
String getContentType() | 获取提交的文件类型 |
long getSize() | 获取文件的大小 |
void write(String path) | 把提交的文件数据写入磁盘文件 (保存到服务器的本地路径) |
二、代码示例
实现程序,通过网页提交一个图片到服务器上。
1)创建 upload.html,放到 webapp 目录中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>上传文件</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="提交">
</form>
</body>
</html>
细节:
- 上传文件一般通过 POST 请求的表单实现
- 在 form 中要加上 multipart/form-data 字段
2)创建 UploadServlet 类
package upload;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part = req.getPart("myfile");
System.out.println(part.getSubmittedFileName());
System.out.println(part.getSize());
System.out.println(part.getContentType());
part.write("C:/yyhjava_project/tmp/result.jpg");
}
}
细节:
-
需要给 UploadServlet 加上 @MultipartConfig 注解!否则服务器代码无法使用 getPart 方法
-
getPart 的 参数 需要和 form 中 input 标签的 name 属性对应
-
客户端一次可以提交多个文件 (使用多个 input 标签),此时服务器可以通过 getParts 获取所有的 Part 对象
二.在JavaWeb中,可以使用HTML的标签来创建文件选择器,让用户能够选择要上传的图片。然后通过Servlet或者Controller接收到这些图片数据,将其保存到服务器指定位置,最后再返回给前端页面进行展示。
下面是一个基本的示例代码(使用Spring MVC):
HTML部分:
<!-- index.jsp -->
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="imageFile">选择图片</label>
<input type="file" id="imageFile" name="imageFile"><br><br>
<button type="submit">提交</button>
</form>
Servlet部分:
// UploadServlet.java
@MultipartConfig // 开启支持文件上传功能
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part imagePart = request.getPart("imageFile"); // 获取上传的图片文件
String fileName = getFileName(imagePart); // 从文件名中获取原始文件名
// 设置保存路径及文件名
String savePath = "C:/path/to/save/" + fileName;
try (InputStream inputStream = imagePart.getInputStream();
OutputStream outputStream = new FileOutputStream(new File(savePath))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException("Error saving file", e);
}
// 重新加载index.jsp页面,展示已经上传成功的图片
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/index.jsp");
dispatcher.forward(request, response);
}
}
Controller部分(使用Spring MVC):
// ImageUploadController.java
@RestController
public class ImageUploadController {
@Autowired
private MultipartResolver multipartResolver;
@PostMapping("/upload")
public ModelAndView uploadImage(@ModelAttribute("imageForm") ImageForm form, BindingResult result) {
if (!result.hasErrors()) {
// 处理表单数据,包括验证、业务逻辑等操作
return new ModelAndView("redirect:/successPage"); // 重定向到成功页面
} else {
return new ModelAndView("errorPage"); // 错误页面
}
}
}
注意事项:
需要配置好相关的servlet容器(比如Tomcat)才能正常运行该程序;
还需要添加必要的依赖库(比如Apache Commons FileUpload);
为了安全起见,应对上传的文件类型、大小等进行限制和校验;