上传图片
前端读取本地文件上传base64图片, node接收存在本地
- 前端代码
$('#btn').on('click', () => {
var file = document.getElementById('fle')
var formData = new FormData()
formData.append('uploadImg', file.files[0]);
formData.append('name', 'zheng');
var reader = new FileReader();
//上传图片最大值(单位字节)( 2 M = 2097152 B )超过2M上传失败
var AllowImgFileSize = 2100000;
var file = $("#fle")[0].files[0];
var imgUrlBase64;
if (file) {
//将文件以Data URL形式读入页面
imgUrlBase64 = reader.readAsDataURL(file);
reader.onload = function (e) {
//var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分(可选可不选,需要与后台沟通)
if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
alert('上传失败,请上传不大于2M的图片!');
return;
} else {
//执行上传操作
console.log(reader.result);
$.post('http://127.0.0.1:6080/upload', { img64: reader.result })
}
}
}
})
- 后端代码
修改bodyParser接收的最大值, 不然会报错
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
router.post('/upload', function(req, res, next) {
let imgData = req.body.img64
var base64Data = imgData.replace(/^data:image\/\w+;base64,/, '')
var dataBuffer = new Buffer(base64Data, 'base64')
fs.writeFile('./public/images/image.png', dataBuffer, function(err) {
if (err) return
console.log('图片保存成功')
})
res.end('ok')
})
前端读取线上图片转换为
var url = "https://img-blog.csdn.net/20180205214208048";
convertImgToBase64(url, function (base64Img) {
//转化后的base64
console.log('线上图片-base64', base64Img);
});
//实现将项目的图片转化成base64
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;
}