iT邦幫忙

4

[JS][Angular] 使用按鈕觸發檔案上傳

  • 分享至 

  • twitterImage
  •  

在做檔案上傳時,想把很醜的 <input type="file"> 換成漂亮的按鈕。

做法:
先將 input file 隱藏,
接著新增一個 button,利用 button 的 onclick 事件來開啟檔案選取視窗。

程式碼:

Javascript 寫法

<form id="form1" runat="server">
    <div>
        <input id="file" type="file" onchange="upload(this)" style="display: none" />
        <button type="button" onclick="file.click()">檔案上傳</button>
    </div>
</form>
<script>
    function upload(e) {
        var file = e.files[0];
        if (!file) {
            return;
        }

        //檔案上傳
        //...
        //檔案上傳

        //上傳後將檔案清除
        e.value = '';
    }
</script>

AngularJS 寫法

<form id="form1" runat="server">
    <div>
        <input id="file" type="file" onchange="angular.element(this).scope().upload(this)" style="display: none" />
        <button type="button" onclick="file.click()">檔案上傳</button>
    </div>
</form>
<script>
    //Controller 內
    $scope.upload = function(e) {
        var file = e.files[0];
        if (!file) {
            return;
        }

        //檔案上傳
        //...
        //檔案上傳

        //上傳後將檔案清除
        e.value = '';
    }
</script>

Angular 寫法

<form id="form1" runat="server">
    <div>
        <input id="file" type="file" (change)="upload($event)" style="display: none" />
        <button type="button" onclick="file.click()">檔案上傳</button>
    </div>
</form>
<script>
    //Component 內
    upload($event) {
        const file = $event.target.files[0];
        if (!file) {
            return;
        }
        
        //檔案上傳
        //...
        //檔案上傳

        //上傳後將檔案清除
        $event.target.value = '';
    }
</script>

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

1
神Q超人
iT邦研究生 5 級 ‧ 2017-10-27 18:34:04

我的草稿裡面一直靜靜的躺著檔案上傳的文章
可是最近工作超忙沒時間處理/images/emoticon/emoticon02.gif

哈哈,等你的文章出爐!!

2
nella17
iT邦新手 5 級 ‧ 2017-10-31 00:36:41
<form id="form1" runat="server">
    <label class="btn btn-outline-dark" for="file1">檔案上傳</label>
    <input class="hidden" id="file1" type="file"/>
</form>
<script>
    document.getElementById("file1")
      .addEventListener("change", function($event) {
          const file = $event.target.files[0];
          if (!file) { return; }

          //檔案上傳
          //...
          //檔案上傳

          //上傳後將檔案清除
          $event.target.value = '';
      });
</script>

jsbin

可以用 label 觸發阿,感謝您提供的資訊,又學到一種新的寫法。

我要留言

立即登入留言