servlet+jsp 上传文件

Servlet + jsp 上传文件

HTML 表单

需要更改 enctype 的值为 multipart/form-data

<form action="/upload/upload" method="post" enctype="multipart/form-data">
       <input type="text" name="uname">
       </br>
       <input type="file" name="myPhoto">
       </br>
       <input type="submit" value="上传">
</form>

JAVA 后台代码

需要使用到 : jspsmartuploadUTF-8.jar 包

@WebServlet("/upload/*")
public class UploadController extends HttpServlet {

   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("UTF-8");
       resp.setContentType("text/html;charset=UTF-8");
       resp.setCharacterEncoding("UTF-8");

       String uri = req.getRequestURI();
       if (uri.equals("/upload/init")){
           req.getRequestDispatcher("/WEB-INF/upload.jsp").forward(req,resp);
      }else if (uri.equals("/upload/upload")){
           // 文件上传
           SmartUpload upload = new SmartUpload();
           // 设置初始值(初始化)
           upload.initialize(this.getServletConfig(),req,resp);

           try {
               // 调用 upload 方法
               upload.upload();

               // 获取上传的文件(多个文件)
               Files files = upload.getFiles();

               // 获取文本框的值
               String str = upload.getRequest().getParameter("");

               // 使用for循环获取每一个文件
               for (int i = 0;i<files.getCount();i++){
                   // 判断文件是否存在
                   File file = files.getFile(i);
                   // 获取文件的名称
                   String fileName = file.getFileName();

                   if (fileName != null && !fileName.isEmpty()){
                       // 上传到服务器的位置
                       String path = this.getServletContext().getRealPath("/people/"+fileName);
                       System.out.println(path);
                       // 准备保存文件
                       java.io.File servletFile = new java.io.File(path);
                       // 判断文件是否存在
                       if (!servletFile.getParentFile().exists()){
                           // 如果不存在,则创建其父路径
                           servletFile.getParentFile().mkdirs();
                      }
                       // 保存文件
                       file.saveAs(path);
                  }
              }

          } catch (SmartUploadException e) {
               e.printStackTrace();
          }

      }
  }
}

如果使用 AJAX 实现文件上传

需要封装文件流对象

function saveHeadImg() {
       var formData = new FormData($("#headImg")[0]);//获取表单中的文件
       $.ajax({
           url:"/people/saveHeadImg",//后台的接口地址
           type:"post",//post请求方式
           data:formData,//参数
           cache: false,
           processData: false,
           contentType: false,
           success:function (res) {
               $('#imgSave').html("上传成功");
          },error:function (res) {
               $('#imgSave').html("上传失败");
          }
      })
  }



posted @ 2020-07-31 09:56  lyy2018  阅读(173)  评论(0)    收藏  举报