1. 程式人生 > >純 js 實現上傳文件支持拖拽

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

add prevent .get target TP isp div tps drag

開發「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 事件裏面對拖動的文件進行操作即可。

插播廣告 ?(? ? ??)嘿嘿

技術分享圖片

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