PC scan code upload PHP implementation
PC-side scan code upload is a hot topic in the development field in recent years. It can easily upload local files to the server, and uses the scan code method to replace the traditional upload method, which is more convenient and efficient. In this article, we will introduce how to use PHP to implement PC scanning and uploading.
For PC-side scanning and uploading, we first need to understand several concepts. The first is the principle of QR code generation and scanning, and the second is the technology of PHP to implement file upload.
QR code generation and scanning principle
QR code is a graphic code that can store a large amount of information. It can be used in a variety of situations, such as links, text, maps, contact details, and more. There are many ways to generate QR codes, the most commonly used of which is to use the JavaScript framework QRCode.js. Through this framework, we can generate corresponding QR codes from text, URL and other information.
When scanning the QR code, we can use the mobile phone scanning software to scan the QR code using the mobile phone camera, and obtain the information represented by the QR code through scanning. For the PC side, we can also use QR code scanning software such as Zbar to scan the QR code.
PHP implements file upload technology
PHP is a very popular server-side scripting language and plays an important role in the field of Web development. For file upload, PHP provides a very convenient file upload class-upload class.
When using the upload class to implement file upload, we only need to simply instantiate the class and use the corresponding method to upload the file. Among them, important methods include: upload(), getFileName(), getErrorMsg(), etc.
PHP implements PC scanning code uploading
With the above basic knowledge, we can start to implement the PC scanning code uploading function. Here we will divide it into two parts, namely background file processing and front-end file generation.
Background file processing
1. Upload file interface
First we need to implement an interface for uploading files, which is used to process the file stream transmitted from the front desk and the file we need to upload. File information. For different file types and file sizes, we need to perform special processing, such as limiting the size and type of uploaded images, etc.
Code example:
<?php header('Content-type: application/json'); $FILE_BASE = './files/'; $MAX_SIZE = 10 * 1024 * 1024;//10M $ALLOW_FILE_SUFFIX = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];//允许上传的文件类型 $max_size_POST = ini_get('post_max_size'); $max_size_UPLOAD = ini_get('upload_max_filesize'); $max_size = min($MAX_SIZE, getBytes($max_size_POST), getBytes($max_size_UPLOAD)); $filename = $_POST['filename']; if (empty($filename)) { echo json_encode(['status' => 'error', 'msg' => 'filename is empty']); return; } if(empty($_FILES) || empty($_FILES['file'])){ echo json_encode(['status' => 'error', 'msg' => 'file is empty']); return; } $file_size = $_FILES['file']['size']; if($file_size > $max_size){ echo json_encode(['status' => 'error', 'msg' => 'file size is too big']); return; } $file_type = strtolower(pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION)); if(!in_array($file_type, $ALLOW_FILE_SUFFIX)){ echo json_encode(['status' => 'error', 'msg' => 'file type is not allowed']); return; } if(!is_dir($FILE_BASE)){ mkdir($FILE_BASE, 0777, true); } $file_path = $FILE_BASE.$filename; if(move_uploaded_file($_FILES["file"]["tmp_name"], $file_path)){ echo json_encode(['status' => 'success', 'msg' => 'upload success']); }else{ echo json_encode(['status' => 'error', 'msg' => 'upload fail']); } function getBytes($val) { $val = trim($val); $last = strtolower($val[strlen($val) - 1]); $val = preg_replace('/[^0-9]/', '', $val); switch ($last) { case 'g': $val *= 1024 * 1024 * 1024; break; case 'm': $val *= 1024 * 1024; break; case 'k': $val *= 1024; break; } return $val; } ?>
2. Generate QR code
Generating QR code can be achieved using the QRCode.js framework. We need to convert the file name and related information to be uploaded into QR code information and then generate the corresponding QR code.
Code example:
<?php $filename = $_POST['filename']; $path = 'http://localhost/'; //服务器地址 $text = urlencode(json_encode(['filename' => $filename, 'path' => $path])); $url = "http://qr.liantu.com/api.php?text=" . $text; echo $url; //返回二维码地址 ?>
Front-end file generation
In the front-end, we need to generate a QR code and display it in the preview box on the right. In addition, we also need to add operation buttons and corresponding prompts for uploading files.
Code example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PC扫码上传</title> <style type="text/css"> .upload { display: inline-block; background: #1B96F3; color: #fff; padding: 8px 12px; border-radius: 4px; cursor: pointer; outline: none; } .upload:hover { background-color: #2A87CB; } .img-preview { width: 200px; height: 200px; overflow: hidden; display: flex; justify-content: center; align-items: center; } .img-preview img { max-width: 100%; max-height: 100%; object-fit: contain; } </style> </head> <body> <div class="wrapper"> <div class="qrcode-container"> <div class="qrcode"></div> </div> <div class="upload-container"> <input type="file" id="file" style="display:none" onchange="uploadFile(this)"/> <button class="upload" onclick="document.getElementById('file').click()">上传文件</button> <div class="alert"></div> </div> <div class="img-preview-container"> <h4>预览</h4> <div class="img-preview"></div> </div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script> <script type="text/javascript"> function createQrcode(url) { var qrcode = new QRCode(document.querySelector('.qrcode'), { text: url, width: 200, height: 200, colorDark: "#000000", colorLight: "#ffffff", correctLevel: QRCode.CorrectLevel.H }); } function showPreview(file) { var fr = new FileReader(); fr.onload = function () { $('<img>').attr('src', fr.result).appendTo('.img-preview'); } fr.readAsDataURL(file); } function uploadFile(obj) { var file = obj.files[0]; var fd = new FormData(); fd.append('file', file); fd.append('filename', file.name); $.ajax({ url: '/upload.php', type: 'POST', data: fd, processData: false, contentType: false, success: function (data) { if (data.status == 'success') { createQrcode(data.msg); showPreview(file); $('.alert').text('上传成功'); } else { $('.alert').text('上传失败'); } }, error: function () { $('.alert').text('上传失败'); } }); } </script> </body> </html>
In summary, we have successfully completed the development of PC scan code upload. In this process, we learned the principles of QR code generation and scanning, as well as the technology of PHP to implement file upload, and combined the two to complete the implementation of the PC scan code upload function. For developers, this more convenient and efficient upload method will become a hot topic and demand in development.
The above is the detailed content of PC scan code upload PHP implementation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea
