Ajax - Upload local file contents without page refresh

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have a page in my web flow where I want to upload a file without refreshing the page. I tried using an Ajax call for that, but failed. I couldn t figure out how to send the data in the uploaded file to the server side/back end for further processing. I m using the Spring MVC framework and I don t want to use PHP.

Can anyone suggest a solution or some sample code with which I can get my job done? I am very new to JavaScript.

One more thing is i have to get back to the same page after going to server side to process uploaded file and return to same page with a string from server side.all this happen without refreshing the current page

Any suggestion would be highly appreciated.

Answers

Assuming you ve already gotten your form built and server-side controller set up to handle the upload, this little snippet should get you on your way to AJAX-y refresh-less file uploading glory!

//create a new FormData reference
//(note: you could use getElementById or querySelector)
var myForm = document.forms.myUploadForm; 
var fd = new FormData(myForm);

//create and open an XHR
var xhr = new XMLHttpRequest();
xhr.open("POST","http://www.example.url/the/path/to/your/upload/controller");

//set up event listeners (optional)
xhr.onreadystatechange = monitorStatusFunction;
xhr.onprogress = updateProgressBarFunction;

//send the form (w/ no page refresh!)
xhr.send(fd);

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/10048175/upload-local-file-contents-without-page-refresh

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils