Home  >  Article  >  Web Front-end  >  Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources

Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources

黄舟
黄舟Original
2017-03-31 13:13:233580browse

Explain a Java code that dynamically generates PC QR code effects based on parameters, and successfully scans and The function of uploading graphics or video resources.

The technical difficulty is average. The key lies in how to integrate a complete set of logical ideas into the project. If called, Which technologies should be covered and the interaction relationships are clarified. In detail, this is an entry-level code reference for everyone to improve.

A rough introduction to the technical issues applied. The front-end method is simple to use. html element layout, just generate Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources QR code, the backendframework is SpringMVC, the structure is simple, the reference is clear, and the two applied The QR code Jar package is: qrcode_swetake.jar.

1. Start with the front end and build the page layout to ensure that the QR code effect can be generated:

Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources

The achieved shaping effect is as shown in the picture above. When the mouse is moved in and out, the hidden QR code effect box will be displayed. Slowly explore how to implement it with CSS. What needs to be explained here is that the QR code only needs one sentence. Can be dynamically generated.

<c:set var="ctx" value="${pageContext.request.contextPath}"></c:set>
<img  src="${ctx}/upload/codeImg.html?userId=${loginUserId}" / alt="Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources" >

Set an Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources tag to dynamically generate the returned QR code image. The height and width can be set according to the actual situation, and then the mobile phone can access it with a beep. Of course, the test Please ensure that the IPs are in the same LAN at this stage.

The scanned pages are also similar. The key lies in how you want to design them, as long as the upload function of my application can be achieved. The plug-in is jquery.form.js, and the main JS methods are as follows:

<input type="file" name="tempFile" id="tempFile"  
    accept= ".avi,.mpg,.mp4,.mov;capture=camera" onchange="previewFile(&#39;tempFile&#39;);"/>
<input type="file" name="tempFile" id="tempFile" 
    accept= "image/jpg,image/JPG,image/jpeg,image/JPEG,image/pdf,image/png;capture=camera" 
    onchange="previewFile(&#39;tempFile&#39;);"/>
    
<script language="javascript">
        function previewFile(id){
      var x = document.getElementById("tempFile");
      if(!x || !x.value) return;
      var patn = /\.jpg$|\.JPG$|\.jpeg$|\.JPEG$|\.pdf$|\.PDF$|\.png$|\.PNG$/;
      var inpType = "image\/jpg,image\/JPG,image\/jpeg,image\/JPEG,image\/pdf,image\/PDF,image\/png,image\/PNG";
      var type = $("#type").val();
      if(type==&#39;video&#39;){
          patn = /\.mp4$|\.MP4$|\.mov$|\.MOV$/;
          inpType = ".MP4,.MOV,.mp4,.mov";
      }
      if(!patn.test(x.value)){   
          if(type==&#39;video&#39;){
              alertMsg("请上传mov、mp4格式的视频");
          }else{
              alertMsg("请上传jpg、png、pdf格式的文件");
          }
      }else{
              initShow();
            $("#uploadForm").ajaxSubmit(options);
      }
       }
     
    var options  = {
        dataType:"json",
        url:&#39;${ctx}/upload/uploadAndSaveFile.html&#39;,    
        type:&#39;post&#39;,    
        contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        success:function(data)  {
            initHide();
            if(data.success){
                //alertCallBack("上传成功<br/>请前往PC端刷新后查阅!",function(){
                    document.location.href="${ctx}/upload/toUploadEndDetail.html";
                //});
            }else{
                alertCallBack(data.message,function(){
                    window.location.reload();
                });
                //alertMsg(data.message);
            }
        },
        error :function(data){
            initHide();
            alertMsg(data);
        },
        beforeSubmit:showRequest  // pre-submit callback
        //clearForm:true 
    };    
   
    function showRequest(formData, jqForm, options) {
        var queryString = $.param(formData);
    }
</script>

Since the above code involves the company's internal logic, there are deletions in some places, but the overall idea has been clearly listed

#. ##We need to talk about an applied UI plug-in, that is, the hint pop-up box effect used by alertMsg.

The attachment resources will be deployed uniformly, and the plug-in adaptive effect is compatible with IE, Google, The built-in styles and functions of mainstream browsers such as 360 and Firefox can also be rewritten by yourself. The specific application is determined by yourself. . Handle the QR code generation technology and resource saving actions from the back end:

/**
     * @Descript :生成二维码图片url
     * @author : Teny_lau
     * @CreatedTime : 2016年11月21日-下午3:44:44
     * @param model
     * @param request
     * @param response
     */
    @RequestMapping("/codeImg")
    public void toCodeImg(Model model, HttpServletRequest request, HttpServletResponse response) {
        String localIp = getInternetIp(request);
        String path = request.getSession().getServletContext().getContextPath();
        String port = StringUtils.getNullBlankStr(request.getServerPort());// 获取服务器端口
        String userId = StringUtils.getNullBlankStr(request.getParameter("userId"));//接收参数
        String params = "userId=" + userId;
        // 字节长度须控制在124个长度以内,否则报异常数组索引值溢出
        String content = localIp + ":" + port + path + "/upload/toUploadMain.html?" + params;
        EncoderHandler encoder = new EncoderHandler();
        encoder.encoderQRCoder(content, response);
    }
     
    private String getInternetIp(HttpServletRequest request) {
        String ip = StringUtils.getNullBlankStr(request.getHeader("x-forwarded-for"));
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = StringUtils.getNullBlankStr(request.getHeader("Proxy-Client-IP"));
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = StringUtils.getNullBlankStr(request.getHeader("WL-Proxy-Client-IP"));
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = StringUtils.getNullBlankStr(request.getRemoteAddr());// 获取客户端IP地址
        }
        String localIp = "";// 获取网段地址
        try {
            InetAddress localInter = InetAddress.getLocalHost();
            localIp = StringUtils.getNullBlankStr(localInter.getHostAddress());
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        }
        if (!ip.equals(localIp) && !"127.0.0.1".equals(ip)) {
            // 当程序获取非服务器网口时,自动重置为本地网口
            ip = localIp;
        }
        if ("127.0.0.1".equals(ip)) {
            // 根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (Exception e) {
                e.printStackTrace();
            }
            ip = StringUtils.getNullBlankStr(inet.getHostAddress());
        }
        // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照&#39;,&#39;分割
        if (ip != null && ip.length() > 15) { // "***.***.***.***".length() = 15
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
 
    /**
     * 提交资源信息
     * 
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("uploadAndSaveFile")
    @ResponseBody
    public void uploadAndSaveFile(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String type = StringUtils.getNullBlankStr(request.getParameter("type"));
            saveUploadFile(request);
            result.put("success", true);
        } catch (RuntimeException run) {
            result.put("success", false);
            result.put("message", run.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传失败<br/>请重新或扫码上传!");
            // FileUtil.deleteFiles(fileNames);
        }
        try {
            response.setContentType("text/html;charset=gbk");
            JSONObject jsonObj = JSONObject.fromObject(result);
            response.getWriter().print(jsonObj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     
    /**
     * @Descript :保存上传资源
     * @author : Teny_lau
     * @CreatedTime : 2016年11月21日-下午3:28:39
     */
    private void saveUploadFile(HttpServletRequest request) {
        String userId = StringUtils.getNullBlankStr(request.getParameter("userId"));//接收参数
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("","");
        List<XXX> flashList = new ArrayList<XXX>();
        String oldFlashName = "";// 旧文件
        //由于以下逻辑存在项目代码,故以下对象均为举例说明,具体要求视项目自行修改
        Old oldEntity = new Old();
        if (flashList != null && flashList.size() > 0) {
            oldEntity = flashList.get(0);
            //获取已上传的旧文件名,便于在插入新文件时,删除旧文件,避免资源过多占用空间内存
            oldFlashName = oldEntity.getFlashName();
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file1 = (CommonsMultipartFile) multipartRequest.getFile("tempFile");// 上传资源参数
        if (file1 != null && !file1.isEmpty()) {
            // 判断上传资源等文件大小 控制在500M以内,自行根据项目要求斟酌
            int maxSize = 500 * 1024 * 1024;
            if (file1.getSize() >= maxSize) {
                throw new RuntimeException("保存失败,文件控制在500M以内");
            }
            String fileName = saveFile(file1, request, oldFlashName);//这里返回的为重命名新文件名称
        }
 
    }
 
    private String saveFile(CommonsMultipartFile file, HttpServletRequest request, String oldFileName) {
        String fileName = file.getOriginalFilename();
        String uploadPath = request.getSession().getServletContext().getRealPath(FILEPATH);
        // 判断是否有上传文件
        File targetFile = null;
        String groupId = StringUtils.getNullBlankStr(request.getParameter("groupId"));//接收参数
        String newTransFileName = DateUtils.getCurrentDateTime14() + groupId + "." + org.apache.commons.lang3.StringUtils.substringAfterLast(fileName, ".");
        String newFilePath = uploadPath + File.separator + newTransFileName;
        try {
            targetFile = new File(new StringBuilder().append(newFilePath).toString());
            // 文件重命名
            file.transferTo(targetFile);
            String oldFilePath = "";
            if (StringUtils.isNotBlank(oldFileName)) {
                oldFilePath = uploadPath + File.separator + oldFileName;
                FileUtil.delSingleFile(oldFilePath);
            }
            // 复制文件到指定盘
            // CopyFileUtil.copyFile(origiNewPath, oldFilePath, true);
             
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newTransFileName;
    }

The codes are pasted one by one. Due to the company logic, the above codes have also been deleted individually, but the overall idea is Functions such as additions, deletions, modifications, and uploads have been displayed here one by one.

Individual tool class methods are as follows:

1. StringUtils.getNullBlankStr

/**
     * 功能描述:
     * 判断字符串是否为null或为空字符串,则返回空字符串""
     *
     * @param obj String
     *            待检查的字符串
     * @return String
     *         如果为null或空字符串(包括只含空格的字符串)则返回"",否则返回原字符串去空格
     */
    public static String getNullBlankStr(Object obj) {
 
        if (obj == null) {
            return "";
        } else {
            return obj.toString().trim();
        }
    }

When the verification is judged to be empty. Action that returns an empty string.

2. DateUtils.getCurrentDateTime14()

/**
     * 获取当前应用服务器的系统日期时间
     * 
     * @return 日期时间字符串,格式:yyyyMMddHHmmss
     */
    public static String getCurrentDateTime14() {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(new Date(System.currentTimeMillis()));
    }

The specific time format can be defined by yourself, depending on the specific situation.

3. For the EncoderHandler and FileUtil tool classes, refer to the attached file source code.

Special Note:

A problem that needs to be reminded of the EncoderHandler here is that the length of bytes received by this method has a maximum limit, that is, it can save a maximum of 124 characters, which exceeds the length. A data out-of-bounds exception will be reported.

public void encoderQRCoder(String content, HttpServletResponse response) {
        try {
            Qrcode handler = new Qrcode();
            handler.setQrcodeErrorCorrect(&#39;M&#39;);
            handler.setQrcodeEncodeMode(&#39;B&#39;);
            handler.setQrcodeVersion(7);
             
            // System.out.println(content);
            byte[] contentBytes = content.getBytes("UTF-8");
             
            BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB);
             
            Graphics2D gs = bufImg.createGraphics();
             
            gs.setBackground(Color.WHITE);
            gs.clearRect(0, 0, 140, 140);
             
            // 设定图像颜色:BLACK
            gs.setColor(Color.BLACK);
             
            // 设置偏移量 不设置肯能导致解析出错
            int pixoff = 2;
            // 输出内容:二维码
            if (contentBytes.length > 0 && contentBytes.length < 124) {
                boolean[][] codeOut = handler.calQrcode(contentBytes);
                for (int i = 0; i < codeOut.length; i++) {
                    for (int j = 0; j < codeOut.length; j++) {
                        if (codeOut[j][i]) {
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            } else {
                System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
            }
             
            gs.dispose();
            bufImg.flush();
             
            // 生成二维码QRCode图片
            ImageIO.write(bufImg, "jpg", response.getOutputStream());
             
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

————————————————————————————————

// 字节长度须控制在124个长度以内,否则报异常数组索引值溢出
        String content = localIp + ":" + port + path + "/upload/toUploadMain.html?" + params;
        EncoderHandler encoder = new EncoderHandler();
        encoder.encoderQRCoder(content, response);

So when the content string is spliced , note that the length must not exceed 124 bytes, otherwise an error will be reported, as shown in the following figure:

Well, the above content is the dynamically generated QR code and upload that will be explained today. Now that you have learned all the knowledge about the resources, if you apes try it out a few times, I believe you can learn a small technique very well. If you have any questions or suggestions, please feel free to comment on the blog.

If the attached resource cannot be downloaded, please move to the link yourself: down.51cto.com/data/2261528

If you have any suggestions or better ideas, welcome to join JAVA Development project discussion group: 214404624. Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources

Use your smart brain to discover newer and more dynamic ideas. Let’s discuss technical research and implementability together.

The above is the detailed content of Sample code using HTML5 to implement the function of scanning PC QR codes and triggering the WAP side to upload resources. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn