亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用JS一鍵上傳文件

使用JS一鍵上傳文件

慕村225694 2022-06-05 11:01:24
我正在嘗試一鍵上傳文件。我可以選擇文件,但無法一鍵將其上傳到服務器上的特定位置。其余部分需要幫助。html:<form><input type="file" id="real-file" class="displaynone"/><button id="custom-button" class="button-input-3">Upload file</button></form>JS:<script type="text/javascript">const realFileBtn = document.getElementById("real-file");const customBtn = document.getElementById("custom-button");customBtn.addEventListener("click", function() {realFileBtn.click();});</script>我很抱歉。我對此比較陌生,并且感覺自己的方式。您能提供的任何幫助將不勝感激。謝謝。
查看完整描述

2 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

瀏覽器不允許 javascript 啟動文件對話框。用戶必須單擊該按鈕。這是一項安全預防措施,可防止欺騙用戶執行此操作。



查看完整回答
反對 回復 2022-06-05
?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

我會從這樣的事情開始。您不需要一堆 javascript 來使一個按鈕以編程方式單擊另一個按鈕。讓一些聰明的 css 完成所有的提升。(我已經用解釋注釋了 css,但如果有任何需要澄清的地方,我很樂意詳細說明。)


這個片段讓你到達一個點,文件輸入的更改會觸發你的函數,并且你有一個對輸入的引用,并通過擴展它的文件和表單。從那里做任何你需要做的事情。


function handleFileChange ({target}) {

  if (target.files.length) {

    // do something with the form.

    // target.form.submit() or whatever

    console.log(target.files);

  }

}


const fileInput = document.querySelector('input');

fileInput.addEventListener('change', handleFileChange);

form {

  /* provides positioning context for the file input (below) */

  position: relative;

  

  /* purely cosmetic */

  background: #0099ff;

  color: white;

  font-weight: bold;

  font-size: 3rem;

}


form div {

  /* purely cosmetic */

  padding: 3rem;

  text-align: center;

  font-family: sans-serif;

  

  /*

  allows clicks to pass through the text

  element and hit the file input instead

  */

  pointer-events: none;

}


input[type=file] {

  /* hides the file input while leaving it clickable */

  opacity: 0;

  

  /*

   positions the file input to occupy the entire

   container, so no matter where you click it triggers

   the file chooser

  */

  position: absolute;

  top: 0;

  left: 0;

  right: 0;

  bottom: 0;

  width: 100%;

}

<form>

  <input type="file" name="some-file" />

  <div>Upload a file</div>

</form>


查看完整回答
反對 回復 2022-06-05
  • 2 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號