純 js 實現上傳文件支持拖拽


開發「bufpay.com 個人即時到賬收款平台」 后台需要支持開發者的微信和支付寶二維碼上傳。

 

<p>
<button class="btn btn-primary" onClick="javascript:document.getElementById('fileupload').click();">批量上傳微信/支付寶支付二維碼</button>
<input style="display:none;" id="fileupload" type="file" name="file" accept="image/*" multiple>
</p>

 

原來的方式是點擊 button 觸發一個 隱藏的 file 的 onchange 事件,從而彈出文件選擇框,選擇文件。

但是有用戶反饋直接拖動收款二維碼進去會方便一些。於是,修改原代碼,在 js 文件中添加

 

<p id="drop_area" onClick="javascript:document.getElementById('fileupload').click();">
<button class="btn btn-primary">批量上傳微信/支付寶支付二維碼</button>
<input style="display:none;" id="fileupload" type="file" name="file" accept="image/*" multiple>
</p>
var dp = document.getElementById('drop_area');
    dp.addEventListener('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    });
    dp.addEventListener("drop", function(e) {
        e.stopPropagation();
        e.preventDefault();
        var files = e.dataTransfer.files;
        // do something upload
    });

 

把 button 的上一級 p 作為一個 drop area 添加監聽 dragover 和 drop 事件,在 drop 事件里面對拖動的文件進行操作即可。

 

插播廣告 ✧(≖ ◡ ≖✿)嘿嘿


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM