Servlet3.0新增了request.getParts()/getPart(String filename) api,用于获取使用multipart/form-data格式传递的http请求的请求体,通常用于获取上传文件。
-
核心代码:
Part part = request.getPart("file");//获取类型为“file”的表单项 String name = part.getHeader("content-disposition");//获取文件名 String random_name = UUID.randomUUID().toString()+ name.substring(name.lastIndexOf("."), name.length() - 1);//生成uuid码,截取文件扩展名 组合成新的唯一文件名 String filename = request.getServletContext().getRealPath("/upload") + "\" + random_name;//获取保存路径(这里获取项目根目录下的upload文件夹路径),拼接成完整文件路径 part.write(filename);//根据完整文件路径写入保存
-
测试案例:
- jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>文件上传</title> </head> <body> <form action="upload" enctype="multipart/form-data" method="post"> 文本一:<input type="text" name="text1"/><br> 文本二:<input type="text" name="text2"/><br> 选择文件:<br> <input type="file" name="fileName"/> <input type="submit" value="上传" />
-
Servlet文件
package control; import java.io.IOException; import java.util.UUID; import javax.servlet.RequestDispatcher; 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; @SuppressWarnings("serial") @WebServlet("/upload") @MultipartConfig public class UploadServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //RequestDispatcher rd = request.getRequestDispatcher("/test2.jsp"); String text1 = request.getParameter("text1"); String text2 = request.getParameter("text2"); System.out.println(text1+" "+text2); Part part = request.getPart("fileName"); String name = part.getHeader("content-disposition"); String random_name = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."), name.length() - 1); String filename = request.getServletContext().getRealPath("/upload") + "\" + random_name; System.out.println(filename); part.write(filename); //rd.forward(request, response); } }
点击上传后,eclipse报错
F:eclipse-workspace.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebappsserveruploadd84a17a2-2ec2-4517-872c-68131d551d16.jpg (系统找不到指定的路径。)
因为eclipse写代码的项目和真正运行的项目不在同一路径
进入上述报错的根路径,新建upload文件夹
再次运行,控制台显示正确的text1、text2以及文件路径值
1111 aaaa F:eclipse-workspace.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebappsserverupload38749453-f2cc-4a05-b877-e21a7718a890.jpg
进入该文件路径查看,文件已经保存
除了图片,音频视频等文件同理。
转载请注明博文来源,有什么问题欢迎在评论栏留言。 ——Kevin_Lu 2020-02-28