Mobile Barcode and QR Code Reader Using HTML5 and ASP.NET

yushulx

Xiao Ling

Posted on April 7, 2022

Mobile Barcode and QR Code Reader Using HTML5 and ASP.NET

On mobile platforms, HTML5 is not only supported by web browsers, such as Chrome, Edge, Safari, Firefox, and Opera, but also web view UI component that used for building native apps. Therefore, even though you are only familiar with web development, you can easily create excellent mobile apps for Android and iOS. This article aims to help web developers to build a mobile barcode and QR code reader using HTML5, ASP.NET and Dynamsoft Barcode Reader SDK. It is a server-side-decoding solution, which includes client-side image capture, HTTP image upload, and server-side barcode and QR code recognition. If you are interested in client-side barcode and QR code recognition, please refer to Build a Barcode Scanner Using JavaScript and Html5. Dynamsoft provides both client-side (JavaScript and WebAssembly) and server-side (.NET and C/C++) SDK for barcode and QR code detection.

Prerequisites

.NET 6 SDK

Steps to Make Mobile Barcode and QR Code Reader in ASP.NET

  1. Create a new ASP.NET project:

    dotnet new mvc -o MvcBarcodeQRCode
    
  2. Add Dynamsoft Barcode Reader SDK to the project:

    dotnet add package BarcodeQRCodeSDK
    
  3. Go to Views/Home/Index.cshtml to add an input element for loading image, a button element for uploading image, a div element for showing the barcode and QR code results, and an img element for displaying image:

    <div class="text-center">
        <h1 class="display-4">ASP.NET Barcode and QR Code Reader</h1>
        <input type="file" id="file" accept="image/*" name="barcodeImage"/>
        <button id="btn-scan" onclick="upload()">Scan</button>
        <div id="results"></div>
        <br>
        <img id="image"/>
    </div>
    

    Then add corresponding JavaScript code to wwwroot/js/site.js:

    document.getElementById("file").addEventListener("change", function () {
        let file = this.files[0];
        let image = document.getElementById('image');
        let reader = new FileReader();
    
        reader.addEventListener("load", function () {
            image.src = reader.result;
        }, false);
    
        if (file) {
            reader.readAsDataURL(file);
        }
    });
    
    function upload() {
        const host = location.hostname
        const protocol = location.protocol
        const uploadPath = '/upload'
        let xhr = new XMLHttpRequest();
        let formData = new FormData();
        let file = document.getElementById('file').files[0];
        formData.append('barcodeImage', file, file.name);
        xhr.open('POST', uploadPath, true);
        xhr.send(formData);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("results").innerHTML = "Detection Results: " + xhr.responseText;
            }
        }
    }
    

    To make the image display appropriately for both desktop and mobile browsers, add the following CSS code to wwwroot/css/site.css:

    img {
      max-width: 100%;
      min-width: 250px;
      height: auto;
    }
    
  4. ASP.NET provides controllers to handle HTTP requests. To quickly create a controller class, we use the code generator:

    dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
    dotnet aspnet-codegenerator controller -name FileController -outDir Controllers
    

    According to the ASP.NET Routing document, we can place a route on the action method to handle HTTP request. The following code is used to upload a file or multiple files in ASP.NET:

    [ApiController]
    public class FileController : Controller
    {
        [HttpPost("/upload")]
        public async Task<IActionResult> Upload()
        {
            var files = Request.Form.Files;        
            var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
    
            foreach (var uploadFile in files)
            {
                var fileName = uploadFile.FileName;
                var filePath = Path.Combine(path, fileName);
    
                using (var stream = System.IO.File.Create(filePath))
                {
                    await uploadFile.CopyToAsync(stream);
                }
    
            }
    
            return Ok();
        }
    }
    
  5. As a file is uploaded, we initialize Dynamsoft Barcode Reader and then call DecodeFile() method to read barcode and QR code. You must get a desktop SDK license to activate the SDK.

    BarcodeQRCodeReader.InitLicense("LICENSE-KEY");
    BarcodeQRCodeReader? reader = BarcodeQRCodeReader.Create();
    
    var output = "No barcode found.";
    foreach (var uploadFile in files)
    {
        var fileName = uploadFile.FileName;
        var filePath = Path.Combine(path, fileName);
    
        using (var stream = System.IO.File.Create(filePath))
        {
            await uploadFile.CopyToAsync(stream);
        }
        if (reader != null)
        {
            var results = reader.DecodeFile(filePath);
            if (results != null)
            {
                output = "";
                foreach (string result in results)
                {
                    output += result + "\n";
                }
            }
            else
            {
                output = "No barcode found.";
            }
        }
    }
    
    if (reader != null)
    {
        reader.Destroy();
    }
    return Ok(output);
    
  6. Run the project:

    dotnet restore
    dotnet run
    

    mobile barcode and QR code reader in HTML5 and ASP.NET

  7. Publish the ASP.NET project:

    dotnet publish --configuration Release
    

Source Code

https://github.com/yushulx/dotnet-barcode-qr-code-sdk/tree/main/example/web

💖 💪 🙅 🚩
yushulx
Xiao Ling

Posted on April 7, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related