html5调用手机摄像头和相册,h5 调用手机摄像头/相册

本文介绍如何扩展上传功能,允许用户同时上传多张图片,并使用JavaScript实现文件大小限制和Base64编码,以便于图片预览。通过扩展`getBase64`函数并结合`uploadChange`事件处理,简化了多张图片上传的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html 部分

js 部分

getBase64: function (file, callback) {

var maxWidth = 640

if (file.files && file.files[0]) {

var thisFile = file.files[0]

// if (thisFile.size > 524288) {

//    this.showToast("图片不能超过512k!");

//  return;

// }

var reader = new FileReader()

reader.onload = function (event) {

var imgUrl = event.target.result

var img = new Image()

img.onload = function () {

var canvasId = 'canvasBase64Imgid',

canvas = document.getElementById(canvasId)

if (canvas != null) {

document.body.removeChild(canvas)

}

var canvas = document.createElement('canvas')

canvas.innerHTML = 'New Canvas'

canvas.setAttribute('id', canvasId)

canvas.style.display = 'none'

document.body.appendChild(canvas)

canvas.width = this.width

canvas.height = this.height

var imageWidth = this.width,

imageHeight = this.height

if (this.width > maxWidth) {

imageWidth = maxWidth

imageHeight = this.height * maxWidth / this.width

canvas.width = imageWidth

canvas.height = imageHeight

}

var context = canvas.getContext('2d')

context.clearRect(0, 0, imageWidth, imageHeight)

context.drawImage(this, 0, 0, imageWidth, imageHeight)

var base64 = canvas.toDataURL('image/png', 1)

var imgbase = base64.substr(22)

callback(imgbase)

// this.imgUrl =

}

img.src = imgUrl

}

reader.readAsDataURL(file.files[0])

}

},

uploadChange: function (event) {

if (event.target.files.length > 0) {

this.files = event.target.files[0] // 提交的图片

this.getBase64(event.target, url => {

document.getElementById("appealimg1").src='data:image/png;base64,' + url

})

}

this.isShowUp = false

}

以上代码,只能上传单张照片,如果需要在同一界面上传多张照片,就要再写一个函数,用新的函数接收下标值,来判断当前点击的是哪一张,在调用uploadChange函数的函数,后面就可以拼接下标值了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值