The asynchronous upload of files in the website is a troublesome problem, but now this problem can be easily solved through jquery;
Use jquery2.1 version, older versions do not support asynchronous file upload function;
Form code:
- <formid="fileUploadForm">
- <inputtype="file"name="file"class="imageUpload"/>
- < span id = "commit" > Commit to server </ span >
- </form>
- <formid="fileUploadForm">
- <inputtype="file"name="file"class="imageUpload"/>
- < span id = "commit" > Commit to server </ span >
- </form>
Create a form with a file input
Script code:
- function uploadFile() {
- // Encapsulate the form as a formData object
- var formData = new FormData($( '#fileUploadForm' )[0]);
- $.ajax({
- url:'http://127.0.0.1:8080/image/',
- type:'POST',
- // upload the formData object as a parameter
- data:formData,
- contentType: false,
- processData: false,
- success:function (data) {
- //Processing after the file is uploaded successfully
- $('#showUploadContent').append('<div>name:'+data.name+'<br/>url:'+data.url+'<img src="http://192.168.1.107/'+data.url+'"></div>')
- }
- })
- }
- $(function () {
- //Add click event for submit button
- $('#commit').click(function () {
- uploadFile();
- })
- })
- function uploadFile() {
- // Encapsulate the form as a formData object
- var formData = new FormData($( '#fileUploadForm' )[0]);
- $.ajax({
- url:'http://127.0.0.1:8080/image/',
- type:'POST',
- // upload the formData object as a parameter
- data:formData,
- contentType: false,
- processData: false,
- success:function (data) {
- //Processing after the file is uploaded successfully
- $('#showUploadContent').append('<div>name:'+data.name+'<br/>url:'+data.url+'<img src="http://192.168.1.107/'+data.url+'"></div>')
- }
- })
- }
- $(function () {
- //Add click event for submit button
- $('#commit').click(function () {
- uploadFile();
- })
- })
NOTE: When the submit button uses <button/> <input type="submit"/>, the page will jump, I use the <span/> element:
<span id="commit" >Commit to server</span>
In this way, there will be no page jumps when uploading files, and asynchronous uploads will be achieved;