input type="file"使用

problem:

In the actual development process, we will meet some of the requirements to upload files. However, the use of native <input type="file" />there are some problems in the use

  • When not upload files, displaying "no file choosen", user friendly interface, non-configurable
  • Upload the same file, it will not trigger changean event, even if the changes made to files
  • If the user clicks "Cancel" during the upload process, has uploaded files will be removed

Solutions

After reading some of the source code, we summed up the following solution. A little underhanded means:

  • The real <input type="file" />hidden, using a custom buttonthrough $refsto trigger file upload, implement a custom display
  • After the file is uploaded, the file has been processed, and <input type="file" />the valueset to null, so that the next even upload the same file will still trigger changeevent
  • Using the above method, click Cancel file is removed, but does not affect the page display

Implementation

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="https://unpkg.com/vue"></script>
    <title>Vue</title>
</head>

<body>
    <div id="app">
        <button type="button" @click="click">
            <span v-if="fileName">重新上传</span>
            <span v-else>上传文件</span>
        </button>
        <span>{{fileName}}</span>
        <input type="file" ref="uploadFile" style="display:none" accept="image/gif, image/jpeg" @change="upload"/>
    </div>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                fileName: ''
            },
            methods: {
                click () {
                    // 偷梁换柱,触发文件上传
                    this.$refs.uploadFile.click();
                },
                upload (event) {
                    let files = event.target.files || event.dataTransfer.files;

                    if (!files.length) {
                        this.fileName = '';
                        return;
                    }
                    this.fileName = files[0].name;

                    // 上传之后调用接口...
                    let params = new FormData();
                    params.append('file', files[0]);
                    console.log(params);

                    this.$refs.uploadFile.value = null; // 移除文件,可以保证上传同样的文件时,也会触发change事件
                }
            }
        })
    </script>
</body>

</html>

Impressions

When it came to issues more to see how others write, draw about the same time solve the problem of a lot of things to learn.

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/11967326.html