前端代码

<form   id="uploadForm"  method="post" enctype="multipart/form-data">
   <label  >上传电子书</label>
   <input type="file"  name="file" >
   <button  id="upload" type="button"  name="button" >上传</button>
</form>
$("#upload").click(function () {
   var formData = new FormData($('#uploadForm')[0]);
   $.ajax({
    type: 'post',
    url: "https://****:8443/fileUpload", //上传文件的请求路径必须是绝对路劲
     data: formData,
     cache: false,
     processData: false,
     contentType: false,
      }).success(function (data) {
        console.log(data);
        alert("上传成功"+data);
        filename=data;
      }).error(function () {
         alert("上传失败");
     });
    });

首先创建一个FormData实例,也就是空对象,将页面中现有form表单将他初始化。通过AJAX提交给后台

后端代码

@PostMapping(value = "/fileUpload")
    @ResponseBody
    public String  fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
            String fileName = file.getOriginalFilename();  // 文件名
            System.out.println(file.getOriginalFilename());
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "C://pdf//"; // 上传后的路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            System.out.println("pdf文件路径为:"+dest.getPath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
                System.out.println("上传pdf文件+++++++++++");
                System.out.println("pdf文件路径为:"+dest.getPath());
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String filename = "/pdf/" + fileName;
          return fileName;


    }

注意

1.@RequestParam(value = “file”) 中的file需要和input中的name属性一致。
2.提交按钮类型Type=“Button”如果为“submit”的话,提交完数据会刷新一次页面。

上传多个文件

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Ajax上传</title>
 <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
 <h1>文件上传</h1>
 <form id="f" enctype="multipart/form-data">
  UserName:<input type="text" name="userName"><br/>
  File1:<input type="file" name="file"><br/>
  File2:<input type="file" name="file"><br/>
  <input type="button" id="btn" value="提交">
 </form>
</body>
<script>
 $(function () {
  $("#btn").on("click",function () {
   //使用FormData对象来提交整个表单,它支持文件的上传
   var formData=new FormData(document.getElementById("f"));
   //额外带来一些数据
   formData.append("age",14);
   //使用ajax提交
   $.ajax("ajaxUpload",{
    type:"post",
    data:formData,
    processData:false,//告诉jquery不要去处理请求的数据格式
    contentType:false,//告诉jquery不要设置请求头的类型
    success:function (data) {
     alert(data);
    }
   });
  })
 })
</script>
</html>

@WebServlet("/ajaxUpload")
@MultipartConfig //开启上传功能
/**
 * @author hh
 */
public class FileUploadServlet extends HttpServlet {
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  req.setCharacterEncoding("utf-8");
  //获取用户名
  String userName=req.getParameter("userName");
  //获取年龄
  String age=req.getParameter("age");
  System.out.println(userName);
  System.out.println(age);
  //获取项目部署的绝对路径
  String uploadPath=req.getServletContext().getRealPath("/photos");
  //构建上传的文件夹
  File dir=new File(uploadPath);
  if(!dir.exists()){
   dir.mkdir();
  }
  //获取所有上传的Part
  Collection<Part> parts= req.getParts();
  for (Part part:parts) {
   //判断上传的类型是否为空,如果为空则不执行上传
   if(part.getContentType()!=null){
    //获取文件名
    String fileName=part.getSubmittedFileName();
    //执行上传
    part.write(uploadPath+File.separator+fileName);
   }
  }
  //响应上传成功
  resp.getWriter().println("uplaod success");
 }
}

更多推荐

使用AJAX实现上传文件