js converts the file file object into an img object

  1. Copy and encapsulate the following code in the xxx.js file, and place it under the project folder utils

    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. Use: import xxx.js file, call method

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

Guess you like

Origin blog.csdn.net/lhh_gxx/article/details/128377119