ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Servlet实现上传文件到服务器

2022-08-26 13:03:24  阅读:171  来源: 互联网

标签:文件 String Servlet request Part 服务器 上传


前端页面(upload.html)

   <!--
       要上传文件,必须将表单的提交方式设置为"post",设置表单的enctype属性为"multipart/form-data"
   -->
   <!-- 表单的action必须以项目的根路径开头,这里假设项目根路径为/servlet -->
   <forom action="/servlet/upload" method="post" enctype="multipart/form-data">
      用户名:<input type="text" name="username"/><br/>
      上传文件:<input type="file" name="uploadFile"/><br/>
      <input type="submit" value="上传"/>
   </form>

后端servlet(UploadServelt)

/*
   使用注解@MultipartConfig 将一个Servlet标识为支持上传文件.
   Servlet将enctype属性值"mulipart/form-data"表单的POST请求封装为Part(jakarta.servlet.http.Part)
   通过Part对象对上传的文件进行操作

   注意:只要前端的表单设置了enctype属性为"multipart/form-data",就一定要在后端的Servlet上加上@MultipartConfig注解
   否则Servlet连表单中的普通文本框提交的数据都无法获取
*/
@MultipartConfig
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     // 设置请求的编码(Tomcat10以上版本不需要)
     request.setCharacterEncoding("utf-8");
     // 通过request对象获取普通文本框提交的内容
     String username = request.getParameter("username");
     // 输出该内容
     System.out.println("username : " + username);
     /*
       通过request对象获取上传的文件
        public Part getPart(String name);
          name参数为文件提交框中name属性的属性值
     */
      Part uploadFile = request.getPart("uploadFile");
     /*
       通过Part对象获取文件上传时的名称
        public String getSubmittedFileName();
     */
      String submittedFileName = uploadFile.getSubmittedFileName();
     /*
       获取要在服务器中存储的真实路径
          注意:getRealPath("/") 该参数必须为"/" 
     */
     String realPath = this.getServletContext().getRealPath("/");
     /*
       通过Part对象将上传的文件保存在服务器
         public void write(String fileName)
     */
     uploadFile.write(realPath + "/" + submittedFileName);
    }
}

标签:文件,String,Servlet,request,Part,服务器,上传
来源: https://www.cnblogs.com/lei101011/p/16627189.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有