Mobile Barcode and QR Code Reader Using HTML5 and ASP.NET
Tags: webdev, aspnet, csharp, qrcode
Published: 2022-04-07 08:38:19

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](https://www.dynamsoft.com/barcode-reader/overview/). 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](https://www.dynamsoft.com/codepool/html5-barcode-reader-javascript-webassembly.html). 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](https://dotnet.microsoft.com/en-us/download/dotnet/6.0)

## Steps to Make Mobile Barcode and QR Code Reader in ASP.NET
1. Create a new ASP.NET project:
    
    ```bash
    dotnet new mvc -o MvcBarcodeQRCode
    ```
2. Add Dynamsoft Barcode Reader SDK to the project:
    
    ```bash
    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:
    
    ```html
    <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`:
    
    ```javascript
    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`:
    
    ```css
    img {
      max-width: 100%;
      min-width: 250px;
      height: auto;
    }
    ```

4. ASP.NET provides [controllers](https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/actions?view=aspnetcore-6.0) to handle HTTP requests. To quickly create a controller class, we use the code generator:
    
    ```bash
    dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
    dotnet aspnet-codegenerator controller -name FileController -outDir Controllers
    ```

    According to the [ASP.NET Routing](https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0) 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:
    
    ```cs
    [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](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr) to activate the SDK.
    
    ```cs
    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:
    
    ```bash
    dotnet restore
    dotnet run
    ```
    
    ![mobile barcode and QR code reader in HTML5 and ASP.NET](https://www.dynamsoft.com/codepool/img/2022/04/asp-net-mobile-barcode-qr-code-reader.png)

7. Publish the ASP.NET project:
    
    ```bash
    dotnet publish --configuration Release
    ```


## Source Code
[https://github.com/yushulx/dotnet-barcode-qr-code-sdk/tree/main/example/web](https://github.com/yushulx/dotnet-barcode-qr-code-sdk/tree/main/example/web)