js将file文件对象转换成img对象

  1. 将以下代码复制封装于xxx.js文件中,放置在项目文件夹utiles下

    export default function readImg (file) {
          
          
    	return new Promise((resolve, reject) => {
          
          
    		const img = new Image()
    		const reader = new FileReader()
    		reader.onload = function (e) {
          
          
    			img.src = e.target.result
    		}
    		reader.onerror = function (e) {
          
          
    			reject(e)
    		}
    		reader.readAsDataURL(file)
    		img.onload = function () {
          
          
    			resolve(img)
    		}
    		img.onerror = function (e) {
          
          
    			reject(e)
    		}
    	})
    }
    
  2. 使用:引入xxx.js文件,调用方法

    // 注意引入路径不要出错
    import readImg from '@/utils/xxx.js'
    
    readImg(file).then(res => {
          
          
    	// 输出图片img对象
    	console.log(res)
    }).catch(err => {
          
          
    	console.log(err)
    })
    

猜你喜欢

转载自blog.csdn.net/lhh_gxx/article/details/128377119