Home >Web Front-end >JS Tutorial >Implement Ajax file upload function

Implement Ajax file upload function

coldplay.xixi
coldplay.xixiforward
2020-12-07 17:53:153437browse

Implement Ajax file upload function

Ajax Tutorial column shares the specific code for Ajax file upload for your reference. The specific content is as follows

Front-end form and JQuery jsp/html code

Using JQury

<script src="static/js/jquery-3.4.1.js"></script>

Front-end form

<form id="form-avatar" enctype="multipart/form-data">
 <p>请选择要上传的文件:</p>
 
 <p><input type="file" name="file" /></p>
 <p><input id="btn-avatar" type="button" value="上传" /></p>
</form>

ajax request server

<script>
 function uploadfile(){
  $.ajax({
   url : "/url/upload",
   data: new FormData($("#form-avatar")[0]),
   type : "POST",
   // 告诉jQuery不要去处理发送的数据,用于对data参数进行序列化处理 这里必须false
   processData : false,
   // 告诉jQuery不要去设置Content-Type请求头
   contentType : false,

   success : function(json) {
    alert("执行成功");
   },
   error : function(json) {
    alert("执行失败");

   }
  });
 }
 $("#btn-avatar").on("click",uploadfile);
</script>

Conroller.java

@PostMapping("/upload")
 public void fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
  System.out.println("走了");
  //上传路径保存设置
  String path = request.getServletContext().getRealPath("/upload");
  File realPath = new File(path);
  if (!realPath.exists()) {
   realPath.mkdir();
  }
  //上传文件地址
  System.out.println("上传文件保存地址:" + realPath);

  //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
  file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));

 }

Result

The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related free learning recommendations: javascript (video)

The above is the detailed content of Implement Ajax file upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete