Servlet3.0简化实现文件上传
Posted pdpq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet3.0简化实现文件上传相关的知识,希望对你有一定的参考价值。
注意事项
- 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>
以上是关于Servlet3.0简化实现文件上传的主要内容,如果未能解决你的问题,请参考以下文章