我们在UI5官方文档上进行搜索Scan,是只能找到一个BarcodeScanner的,这个API是无法实现我们这个需求的,所以如果有朋友收到这种需求,不想做的情况下,是可以推脱一下,把问题抛给SAP的(笑)。既然写了博客,也是可以推断到我没有进行推脱哈(笑)。不过非标准功能,使用第三方库进行开发始终是有风险,可以自行评估下。我们下面直接进入今天的主题吧。
实现这个需求使用了一个第三方的开源库 mebjas/html5-qrcode
Gitthub:https://github.com/mebjas/html5-qrcode
参考博客:QR Code scanner using HTML5 and Javascript | Minhaz’s Blog
那么接下来和引入其他第三库的步骤是一模一样的。
在webapp里面创建一个文件夹lib,再在里面新建一个js文件html5-qrcode.min.js
把这个链接
https://raw.githubusercontent.com/mebjas/html5-qrcode/master/minified/html5-qrcode.min.js
下面的js 复制一份,然后粘贴进刚刚创建的html5-qrcode.min.js里面。文件结构见下截图
然后view里面可以使用一个layout来充当我们扫描控件的容器
<mvc:View controllerName="YTEST_QR_CODE.controller.App" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"xmlns:l="sap.ui.layout" displayBlock="true" xmlns="sap.m"><App><pages><Page title="{i18n>title}"><Panel headerText="Static (decorative) HTML Provided as a String With Preserved DOM After Rendering"><content><l:HorizontalLayout id="staticContentLayout"><l:content></l:content></l:HorizontalLayout></content></Panel></Page></pages></App>
</mvc:View>
contoller代码,在onInit方法里面放个input当成qrcode的容器,在onAfterRendering里面
sap.ui.define(["sap/ui/core/mvc/Controller","sap/ui/core/HTML","sap/m/MessageToast","YTEST_QR_CODE/lib/html5-qrcode.min"
], function(Controller, HTML, MessageToast, Html5Qrcodejs) {"use strict";return Controller.extend("YTEST_QR_CODE.controller.App", {//定时器onInit: function() {//MessageToast.show("2018年9月20日,第四次当选自民党总裁;2020年8月28日,宣布辞任首相,于9月16日正式卸任并离开首相官"); // MessageToast.show("777",{"duration":5000})var oHtml = this.byId("htmlControl");if (!oHtml) {var sId = this.createId("htmlControl");oHtml = new HTML(sId, {// the static content as a long string literalcontent: "<div id='testreader' width='600px'></div>" +"<input type='file' id='qr-input-file' accept='image/*' capture >",preferDOM: false});var oLayout = this.byId("staticContentLayout");oLayout.addContent(oHtml);}},onAfterRendering: function() {function onScanSuccess(decodedText, decodedResult) {// Handle on success condition with the decoded text or result.console.log(`Scan result: ${decodedText}`, decodedResult);MessageToast.show(decodedText);};var html5QrcodeScanner = new Html5QrcodeScanner("testreader", {fps: 10,qrbox: 250});html5QrcodeScanner.render(onScanSuccess);},onScanSuccess: function(decodedText, decodedResult) {// handle the scanned code as you like, for example:// console.log(`Code matched = ${decodedText}`, decodedResult);},onScanFailure: function(error) {// handle scan failure, usually better to ignore and keep scanning.// for example:// console.warn(`Code scan error = ${error}`);},onPress: function() {}});
});