Created
October 2, 2015 14:50
-
-
Save morningtoast/65d3d73da682c99321ae to your computer and use it in GitHub Desktop.
Ajax upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <style> | |
| .container { | |
| width: 500px; | |
| margin: 0 auto; | |
| } | |
| .progress_outer { | |
| border: 1px solid #000; | |
| } | |
| .progress { | |
| width: 0%; | |
| background: #DEDEDE; | |
| height: 20px; | |
| } | |
| </style> | |
| <form id="file-form" action="handler.php" method="POST"> | |
| <label for="file-select">Pick stuff</label> | |
| <p id="list"></p> | |
| <input type="file" id="file-select" name="photos[]" multiple style="position:absolute;left:-99999px;top:-9999px"/> | |
| <button type="submit" id="upload-button">Upload</button> | |
| </form> | |
| <div class='progress_outer'> | |
| <div id='_progress' class='progress'></div> | |
| </div> | |
| <script> | |
| var form = document.getElementById('file-form'); | |
| var fileSelect = document.getElementById('file-select'); | |
| var uploadButton = document.getElementById('upload-button'); | |
| var _progress = document.getElementById('_progress'); | |
| fileSelect.onchange = function() { | |
| var files = fileSelect.files; | |
| for (var i = 0; i < files.length; i++) { | |
| var file = files[i]; | |
| console.log(file); | |
| document.getElementById("list").innerHTML += file.name+"<br>"; | |
| } | |
| } | |
| form.onsubmit = function(event) { | |
| event.preventDefault(); | |
| // Update button text. | |
| uploadButton.innerHTML = 'Uploading...'; | |
| // The rest of the code will go here... | |
| var files = fileSelect.files; | |
| var formData = new FormData(); | |
| // Loop through each of the selected files. | |
| for (var i = 0; i < files.length; i++) { | |
| var file = files[i]; | |
| // Check the file type. | |
| if (!file.type.match('image.*')) { | |
| continue; | |
| } | |
| // Add the file to the request. | |
| formData.append('photos[]', file, file.name); | |
| } | |
| var request = new XMLHttpRequest(); | |
| request.onreadystatechange = function(){ | |
| if(request.readyState == 4){ | |
| try { | |
| var resp = JSON.parse(request.response); | |
| } catch (e){ | |
| var resp = { | |
| status: 'error', | |
| data: 'Unknown error occurred: [' + request.responseText + ']' | |
| }; | |
| } | |
| console.log(resp.status + ': ' + resp.data); | |
| } | |
| }; | |
| request.upload.addEventListener('progress', function(e){ | |
| _progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%'; | |
| }, false); | |
| request.open('POST', 'uplhandle.php'); | |
| request.send(formData); | |
| } | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment