zl程序教程

您现在的位置是:首页 >  前端

当前栏目

javascript 上传图片时预览图片的两种方法

JavaScript上传方法 图片 两种 预览
2023-09-11 14:19:35 时间

一、转化为base64位预览

 if(window.FileReader)
 {
                        let reader = new FileReader()
                        reader.readAsDataURL(file[i])
                        reader.onload = function(e) {
                        that.imgShow.push(this.result);
  }
 else {
        alert("Not supported by your browser!");
        }

二、使用createObjectURL生成兼容性更好,createObjectURL得到的是一个blob协议格式的地址

  function getFileURL(file)
            {
                    let url = null;
                    if (window.createObjectURL != undefined) {
                        url = window.createObjectURL(file)
                    } else if (window.URL != undefined) {
                        url = window.URL.createObjectURL(file)
                    } else if (window.webkitURL != undefined) {
                        url = window.webkitURL.createObjectURL(file)
                    }
                    return url;
            }

生成效果

相关参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL