There is still a difference between uploading a single file and uploading a normal field. Here are mainly two processing methods for submitting them in a form, one is to directly click the submit button to submit the form, and the other is to click to submit through js.
Before making a comparison, paste the controller code
@ResponseBody @RequestMapping("upload") public boolean upload(User user,MultipartRequest mreq){ System.out.println("user:"+user.toString()); MultipartFile mfile=mreq.getFile("file"); System.out.println("Is the file empty:"+mfile.isEmpty()); return true; }
1. Click the button to submit the form
1.1 The form code of the jsp page is as follows
form submission <form action="ProjectFormMvn/user/upload" enctype="multipart/form-data" method="post"> 名称:<input type="text" name="account" /><br/> 文件:<input type="file" name="file"/><br/> <input type="button" value="提交"/> </form>
1.2 Click Submit
As you can see from the console, the controller has received the value normally.
2. Submit via js
2.1 The jsp page code is as follows
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> function clickMe(){ var form=document.getElementById("MyForm"), formData=new FormData(form); $.ajax({ url:'/ProjectForMvn/user/upload', type:'POST', data:formData, processData:false, contentType:false, success:function(data){ alert(data); } }) } </script> js submit <form action="###" enctype="multipart/form-data" method="post" id="MyForm"> 名称:<input type="text" name="account" /><br/> 文件:<input type="file" name="file"/><br/> <input type="button" onclick="clickMe();" value="提交"/> </form>
2.2 Click Submit
There are thousands of ajax submission methods in js. Only this one is introduced here, which mainly involves the application of FormData.