因为, JS 是客户端代码, 除非是用户上传文件,否则,在默认情况下,JS不能操作客户端的文件
而如果是上传文件的话,是服务器端代码处理的,也不是JS的范畴
这个简单代码:var read = new FileReader()
read.readAsDataURL(files)
read.onload = function (e) {
var src = e.target.result
$("#img")..attr("src", src)
}
function convertImgToBase64(url, callback, outputFormat){var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image
img.crossOrigin = 'Anonymous'
img.onload = function(){
canvas.height = img.height
canvas.width = img.width
ctx.drawImage(img,0,0)
var dataURL = canvas.toDataURL(outputFormat || 'image/png')
callback.call(this, dataURL)
canvas = null
}
img.src = url
}
//图片地址
var imagePath='image.png'
convertImgToBase64(imagePath, function(base64Img){
// Base64DataURL
})