原生js上傳檔案,使用new FormData()

來源:互聯網
上載者:User

標籤:排列   pre   需要   核心   parse   obj   格式   change   內容   

 當建立一個內容較多的表單,表單裡面又有了檔案上傳,檔案上傳也需要表單提交,單一的上傳檔案很好操作;

<form action="介面" enctype="multipart/form-data" method="post">    <input type="file" name="uploadFile"/>    <input type="submit" value="提交"/></form>

但是,正常提交資料和上傳檔案不是一個介面,後台接收參數的方式也是不一樣的;這就需要兩個form表單,但是form表單是不能嵌套的;還有就是表單的內容是按照順序排列的,穿件兩個獨立的表單,寫樣式會很麻煩;

  因此需要一個動態建立form表的js代碼

這個方法只支援到IE10,IE10以下不支援new FormData();

//擷取檔案
function addFile() {
   document.getElementById(‘test1‘).value = "";
var file = document.querySelector(‘input[type=file]‘).files[0];//IE10以下不支援
var typeStr="image/jpg,image/png,image/gif,image/jpeg";
if(typeStr.indexOf(file.type)>=0){
document.getElementById(‘test1‘).value = file.name;
if (file.size > 2097152) {
alert("上傳的檔案不能大於2M");
return;
}else{
     upload(path,file)
    }
}else{
alert("請上傳格式為jpg、png、gif、jpeg的圖片");
}

//上傳檔案
function
upload(path,theFormFile) { var fd = new FormData(); fd.append(‘file1‘, theFormFile);//上傳的檔案: 鍵名,索引值 var url = path;//介面 url = url ? url : ‘‘; var XHR = null; if (window.XMLHttpRequest) { // 非IE核心 XHR = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE核心,這裡早期IE版本不同,具體可以查下 XHR = new ActiveXObject("Microsoft.XMLHTTP"); } else { XHR = null; } if (XHR) { XHR.open("POST", url); XHR.onreadystatechange = function() { if (XHR.readyState == 4 && XHR.status == 200) { var resultValue = XHR.responseText; var data = JSON.parse(resultValue); XHR = null; } } XHR.send(fd); } };

 

原生js上傳檔案,使用new FormData()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.