早期的瀏覽器並不支援透過Ajax上傳檔案的作法,因此常都需要透過Flash的元件來做到一些有互動性的檔案上傳。
在瀏覽器開始支援後(對,我就是說IE!),Ajax上傳檔案的作法才開始應用,所以需要注意瀏覽器的版本。
瀏覽器版本資訊
IE
|
FIREFOX
|
CHROME
|
SAFARI
|
OPERA
|
10.0+
|
4.0+
|
7.0+
|
5+
|
12+
|
Sample Code
<!-- HTML --> <input type='file' name='upload' id='file-select' /> <!-- Javascript --> <script> var fileSelect = document.getElementById('file-select'); // Get the selected files from the input. var files = fileSelect.files;//It’s an array. // Create a new FormData object. 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.可利用type屬性篩選,這裡只取圖片 if (!file.type.match('image.*')) { continue; } // Add the file to the request.這裡的第一個參數等於QueryString的name,第二個參數等於Value formData.append('upload', file, file.name); } //接著可透過JQuery或是自己弄個XMLHttpRequest的方式Send Form //JQuery $.ajax({ url: '/WebApp/uploadFile.action',//php,jsp and etc.. type: 'POST', data: formdata, cache: false, dataType: 'json', processData: false, // Don't process the files contentType: false, // Set content type to false as jQuery will tell the server its a query string request success: function(data, textStatus, jqXHR) { // Handle errors here console.log('Success: ' + textStatus); //STOP LOADING SPINNER }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors here console.log('Errors: ' + textStatus); // STOP LOADING SPINNER } }); //XMLHttpRequest // Set up the request. var xhr = new XMLHttpRequest(); // Open the connection. xhr.open('POST', 'handler.php', true); // Set up a handler for when the request finishes. xhr.onload = function () { if (xhr.status === 200) { // File(s) uploaded. //uploadButton.innerHTML = 'Upload';
alert('Upload Success!');} else { alert('An error occurred!'); } }; // Send the Data. xhr.send(formData); </script>
參考資料