Home > Web Front-end > JS Tutorial > body text

Implement Ajax file upload function

coldplay.xixi
Release: 2020-12-07 17:53:15
forward
3406 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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()));

 }
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template