Load asynchronous file operation using jquery

I want to upload files asynchronously using jQuery. This is my HTML:

<input type="file" id="f" name="f"/> <input id="upload" type="button" value="Upload"/> 

And here is my JavaScript code:

 $(document).ready(function () { $("#upload").click(function () { var filename = $("#f").val(); $.ajax({ type: "POST", url: "addFile.do", enctype: 'multipart/form-data', data: { file: filename }, success: function () { alert("All Files Have Been Uploaded "); } }); }); }); 

I only get file names instead of the actual file I downloaded

I use this plugin to upload files.

+6
source share
1 answer

Unlike your opinion, the code does NOT use this plugin to upload files. Instead, you explicitly make an ajax request. The error occurs because the value of <input type="file"> is the name of the file, and this is the only data that you send in the request.

Instead, you need to bind the form using $(form).ajaxform() ; then in the click handler you can trigger a submit event on the form.

So something like the following should do the trick:

HTML:

 <form method="post" action="addFile.do"> <input type="file" id="f" name="f"/> <input id="upload" type="button" value="Upload"/> </form> 

And JavaScript:

 $('form').ajaxform({ success: function () { alert("All Files Have Been Uploaded "); } }); $("#upload").click(function() { $('form').submit(); }); 
+1
source

Source: https://habr.com/ru/post/969939/


All Articles