码迷,mamicode.com
首页 > Web开发 > 详细

Servlet3.0简化实现文件上传

时间:2019-12-14 15:54:50      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:time()   lang   upload   NPU   span   isp   char   提交   ted   

注意事项

  • 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简化实现文件上传

标签:time()   lang   upload   NPU   span   isp   char   提交   ted   

原文地址:https://www.cnblogs.com/pdpq/p/12039576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!