I'm trying to make ajax file upload . I read that it is not possible to do that without using iframe
.
I wrote :
<iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="yes"></iframe> <form id="myForm" action="file-component" method="post" enctype="multipart/form-data" target="uploadTrg"> File: <input type="file" name="file"> <input type="submit" value="Submit" id="submitBtn"/> </form>
and using jquery form plugin :
$('#myForm').ajaxForm({ dataType: 'json', success: function(data){ alert(data.toSource()); } });
The Result :
the file is uploaded successfully and I can see the uploaded file , but a dialog box appears :
since I send back a json result to display the file name + size etc ..
My Question : How can I use the iFrame to be able to make " ajax file upload".
Note:
Thanks
File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .
This feature allows you to upload and remove files asynchronously. When multiple files are chosen in Asynchronous upload,files will be uploaded one by one to the server. User interaction with the page will not be interrupted at the time of upload. User can also remove the file even after uploading.
I will answer my question , I think I found the solution. These are the steps that I followed to achieve the goal :
The final code looks like this:
<!-- Attach a file --> <iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="yes"></iframe> <form id="myForm" action="http://example.com/file-upload-service" method="post" enctype="multipart/form-data" target="uploadTrg"> File: <input type="file" name="file"> <input type="submit" value="Submit" id="submitBtn"/> </form> <div id="ajaxResultTest"></div>
javascript :
$("iframe").load(function(){ // ok , now you know that the file is uploaded , you can do what you want , for example tell the user that the file is uploaded alert("The file is uploaded"); // or you can has your own technique to display the uploaded file name + id ? $.post('http://example.com/file-upload-service?do=getLastFile',null,function(attachment){ // add the last uploaded file , so the user can see the uploaded files $("#ajaxResultTest").append("<h4>" + attachment.name + ":" + attachment.id "</h4>"); },'json'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With