因为之前OA系统财务上传凭证的时候,要拿手机拍,传到电脑上上传,为了方便财务上传凭证,老大让做一个利用电脑摄像头拍照上传的功能:
使用技术:
WebCam.js
FastDFS
实现原理:
前端调用webcam的方法进行拍照,生成base64格式,然后把base64传入后端进行解码与保存
前端代码(只选取关键代码):
<script language="JavaScript">Webcam.set({width: 800, //照片的宽度height: 600, //照片的高度image_format: 'jpeg', //照片格式jpeg_quality: 90 //照片质量});Webcam.attach( '#my_camera' );//将拍摄区域展示在id为my_camera的div中</script><!-- A button for taking snaps --><form><input type=button value="Take Snapshot" onClick="take_snapshot()"></form><!-- Code to handle taking the snapshot and displaying it locally --><script language="JavaScript">function take_snapshot() {// take snapshot and get image dataWebcam.snap( function(data_uri) {// display results in pageconsole.log(data_uri);//Base64格式document.getElementById('results').innerHTML ='<h2>Here is your image:</h2>' +'<img src="'+data_uri+'"/>';} );}</script>
可以设置的参数:
后台上传(Base64转MultipartFile):
import org.springframework.web.multipart.MultipartFile;import sun.misc.BASE64Decoder;import java.io.*;public class BASE64DecodedMultipartFile implements MultipartFile {private final byte[] imgContent;private final String header;public BASE64DecodedMultipartFile(byte[] imgContent, String header) {this.imgContent = imgContent;this.header = header.split(";")[0];}@Overridepublic String getName() {// TODO - implementation depends on your requirementsreturn System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];}@Overridepublic String getOriginalFilename() {// TODO - implementation depends on your requirementsreturn System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];}@Overridepublic String getContentType() {// TODO - implementation depends on your requirementsreturn header.split(":")[1];}@Overridepublic boolean isEmpty() {return imgContent == null || imgContent.length == 0;}@Overridepublic long getSize() {return imgContent.length;}@Overridepublic byte[] getBytes() throws IOException {return imgContent;}@Overridepublic InputStream getInputStream() throws IOException {return new ByteArrayInputStream(imgContent);}@Overridepublic void transferTo(File dest) throws IOException, IllegalStateException {new FileOutputStream(dest).write(imgContent);}/*** base64转MultipartFile文件** @param base64* @return*/public static MultipartFile base64ToMultipart(String base64) {try {String[] baseStrs = base64.split(",");BASE64Decoder decoder = new BASE64Decoder();byte[] b = new byte[0];b = decoder.decodeBuffer(baseStrs[1]);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {b[i] += 256;}}return new BASE64DecodedMultipartFile(b, baseStrs[0]);} catch (IOException e) {e.printStackTrace();return null;}}}
转为MultipartFile,再调用fasetdfs的上传接口即可完成上传文件的操作。
chrome在http调用摄像头设置开启:
chrome://flags/#unsafely-treat-insecure-origin-as-secure
然后:
改为enabled,在框中输入你的地址:http://xxx.xx.xx.xx:8080
