注意事项
- POST请求可以传输二进制数据,而GET只能传输文本信息
- form表单标签中声明属性 enctype="multipart/form-data"
- 给Servlet添加注解@MultipartConfig,开启Servlet3.0文件上传组件开关
Servlet实现
@WebServlet(name = "UploadServlet",value = "/upload") @MultipartConfig public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String nickname = request.getParameter("nickname"); //文件上传 Part filePart = request.getPart("headIcon"); String header = filePart.getHeader("Content-Disposition"); String fileName = this.getFileName(header); fileName = new Date().getTime() + fileName; //获取保存上传文件的文件夹的真实物理路径 String uploadDir = this.getServletContext().getRealPath("/upload"); //构建上传文件的完整路径 String fileFullPath = uploadDir + File.separator + fileName; //输出文件 filePart.write(fileFullPath); } private String getFileName(String headerInfo){ String[] arr = headerInfo.split("\""); return arr[arr.length - 1]; }
Html示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> 昵称:<input type="text" name="nickname"><br><br> 头像:<input type="file" name="headIcon"><br><br> <input type="submit" value="提交"> </form> </body> </html>
原文地址:https://www.cnblogs.com/pdpq/p/12039576.html
时间: 2024-11-05 19:27:06