最近在做项目的时候,遇到了一个问题,客户提出要只能拍照上传,不能从相册中选择,关于input标签上的capture="camera",在没有打包之前,从手机浏览器打开,确实是直接调起摄像头,但是打包成apk之后,就失效了,于是乎,不断的百度百度百度.......
这样的:
这样的:
看了又看,找了又找,最终没有找到想要的结果。
因为是vue项目,很少用到H5+的方法,主要是不方便调试,看不到调试结果,没有办法,不得不用了,于是
var cmr = plus.camera.getCamera(); //获取摄像头管理对象
//进行拍照操作
cmr.captureImage(function (path) {
// 通过URL参数获取目录对象或文件对象
plus.io.resolveLocalFileSystemURL(path, function (entry) {
//获取文件数据
//不知道为何,这里获取到的file,不能直接转换传值调用接口
entry.file(function (file) {
})
})
})
下边的调试,就不一一复述了,直接上完整代码
<template>
<div class="file-box">
<!--照片区域-->
<div class="camera" @click="camera">+ 拍摄现场照片</div>
<div class="img-box">
<img :src="fileSrc" alt="" />
</div>
</div>
</template>
<script>
//vue自带的el-upload上传组件,是直接在action上给到服务器地址的,这里要自己封装一个接口
import { upLoadImg } from "@/api/demo/demo";
export default {
data() {
return {
fileSrc: "",
};
},
methods: {
//1,先将base64转换为blob
dataURLtoBlob(dataurl) {
var arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
//2,再将blob转换为file
blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
theBlob.name = fileName; // 文件名
return new File([theBlob], fileName, {
type: theBlob.type,
lastModified: Date.now(),
});
},
// 调用摄像头
camera() {
let that = this;
var cmr = plus.camera.getCamera(); //获取摄像头管理对象
//进行拍照操作
cmr.captureImage(function (path) {
// 通过URL参数获取目录对象或文件对象
plus.io.resolveLocalFileSystemURL(path, function (entry) {
let reader = null;
//获取文件数据
entry.file(function (file) {
reader = new plus.io.FileReader(); // 文件系统中的读取文件对象,用于获取文件的内容
reader.onload = function (e) {};
reader.readAsDataURL(file);
reader.onloadend = function (e) {
let dataBase = e.target.result; // 获取Base64,FileReader()返回
let blob = that.dataURLtoBlob(dataBase);//Base64转Blob
let file1 = that.blobToFile(blob, file.name);//Blob转File
that.toupLoad(file1);//上传
};
});
});
});
},
toupLoad(format) {
//将File按后端要求放到formdata中以二进制流上传
let parm = new FormData();
parm.append("file", format);
upLoadImg(parm).then((res) => {
console.log("res", res.fileName);
this.fileSrc = res.fileName
});
},
},
};
</script>
好了,就到这里了,各位大神有好的方法,欢迎批评指出(附源码哦)
有不懂的小伙伴,欢迎私信留言