AJAX+H5 上傳檔案+進度條

來源:互聯網
上載者:User

1.捨去form表單改為使用新型的formData進行傳輸

2.頁面上的上傳檔案控制項:

<input type="file" id="file" class="mr10 ml10 input-medium">
3.ajax實現上傳:

function uploadSaveProjects(obj){    var fileObj = document.getElementById("file").files[0]; // 擷取檔案對象    var FileController = baseUrl + "project/upload";                    // 接收上傳檔案的後台地址     // FormData 對象    var form = new FormData();    form.append("author", "hooyes");                        // 可以增加表單資料    form.append("file", fileObj);                           // 檔案對象    // XMLHttpRequest 對象    var xhr = new XMLHttpRequest();    xhr.open("post", FileController, true);    xhr.onload = function () {        alert("上傳完成!");    };    // 實現進度條功能    // xhr.upload.addEventListener("progress", progressFunction, false);    xhr.send(form);}

4.後台可以使用任何語言接受進行上傳,增加一個進度條,使用h5標籤

<progress  id="progressBar" value="0" max="100"></progress><span id="percentage"></span>

5.增加對進度條的控制js事件

function progressFunction(evt) {    var progressBar = document.getElementById("progressBar");    var percentageDiv = document.getElementById("percentage");    if (evt.lengthComputable) {        progressBar.max = evt.total;        progressBar.value = evt.loaded;        percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";    }}

6.formData到底是個什麼東西?

XMLHttpRequest Level 2添加了一個新的介面FormData.利用FormData對象,我們可以通過JavaScript用一些索引值對來類比一系列表單控制項,我們還可以使用XMLHttpRequest的send()方法來非同步提交這個"表單".比起普通的ajax,使用FormData的最大優點就是我們可以非同步上傳一個二進位檔案.

所有主流瀏覽器的較新版本都已經支援這個對象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。

詳細介紹:http://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.