js实现图片的预览

1.html代码

<label for="officeId">
                                Replace
                                <input type="file" style="display: none;" name="TeacherCertificate" multiple accept=".png,.jpg,.jpeg" id="officeId" placeholder="replace" />
                            </label>

2.file文件转base64

   function fileToBase64(file){
        let that = this,
        reader = new FileReader();
        reader.readAsDataURL(file);
        return new Promise((resolve, reject) => {
            reader.onload = function (e) { //这是一个异步操作
                if (this.result) {
                    resolve(this.result)
                } else {
                    reject("err")
                }

            }
        })
    }
      $('#officeId').change(function (e) {
            console.log(e)
            let files = $('#officeId')[0].files
            console.log(files,555)
            if (files.length < 3 || files.length > 5) {
                alert('Upload 5 pictures at most and 3 pictures at least')
                return
            } else {

                arr = []
                for (let i = 0; i < files.length; i++) {
                    arr.push(fileBolb(files[i]))
                    //arr.push(window.URL.createObjectURL(files[i]))
                    //fileToBase64(files[i]).then(res => {
                       
                    //    arr.push(res)  /
                       
                    //})
                }
                //arr[0] //多文件拿到的值是undefined,单文件可以准确拿到值   //因为这里拿到的值是异步的
                index = 0
                console.log(index)
                console.log(arr)
                console.log(arr[0])
                $('.officeImg').attr('src', arr[index])
              
            }
        })

2.file转blob

    function fileBolb(file) {
        return window.URL.createObjectURL(file)
    }


//多文件上传可以用这个

猜你喜欢

转载自blog.csdn.net/fankse/article/details/118196408