Quantcast
Channel: Xiao Ling – Dynamsoft Developers
Viewing all articles
Browse latest Browse all 239

Uploading Scanned Documents in Windows 10 Laravel Project

$
0
0

Laravel is a PHP Framework. This article shares how to use Dynamic Web TWAIN to scan and upload documents in a Laravel project.

Installation

  • Composer
  • Laravel:
    composer global require laravel/installer

Dynamic Web TWAIN for Laravel

Create a Laravel project skeleton:

composer create-project --prefer-dist laravel/laravel web-document-scan

Now let’s do something to Laravel controller, blade template and routes.

Controller

Create a controller:

php artisan make:controller DWTUploadController

The command will generate a new file – app\Http\Controllers\DWTUploadController.php.Add a page() function to render the blade template and add an upload() function to save uploaded files to images folder:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class DWTUploadController extends Controller
{
    function page()
    {
     return view('dwt_upload');
    }

    function upload(Request $request)
    {
     $validation = Validator::make($request->all(), [
      'RemoteFile' => 'required|image|mimes:png,pdf,jpeg,jpg,gif'
     ]);
     if($validation->passes())
     {
      $image = $request->file('RemoteFile');
      $image->move(public_path('images'), $image->getClientOriginalName());
      return response()->json([
       'message'   => 'Successfully uploaded.'
      ]);
     }
     else
     {
      return response()->json([
       'message'   => $validation->errors()->all()
      ]);
     }
    }
}

Template

Create a blade template at resources\views\dwt_upload.blade.php. The template file contains all web front-end code.

<!DOCTYPE html>
<html>

<head>
    <title>Dynamic Web TWAIN for Laravel</title>
    <script type="text/javascript" src="http://tst.dynamsoft.com/libs/dwt/15.0/dynamsoft.webtwain.min.js"> </script>
    <meta name="_token" content="{{csrf_token()}}" />
</head>

<body>
    <h3>Dynamic Web TWAIN for Laravel</h3>
    <div id="dwtcontrolContainer"></div>
    <input type="button" value="Load Image" onclick="loadImage();" />
    <input type="button" value="Scan Image" onclick="acquireImage();" />
    <input id="btnUpload" type="button" value="Upload Image" onclick="upload()">

    <script>
        var DWObject;
        Dynamsoft.WebTwainEnv.AutoLoad = false;
        Dynamsoft.WebTwainEnv.Containers = [{
            ContainerId: 'dwtcontrolContainer',
            Width: '480px',
            Height: '640px'
        }];
        Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady);
        Dynamsoft.WebTwainEnv.Trial = true;
        Dynamsoft.WebTwainEnv.ProductKey = "LICENSE-KEY
        Dynamsoft.WebTwainEnv.Load();

        function Dynamsoft_OnReady() {
            DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer');
            var token = document.querySelector("meta[name='_token']").getAttribute("content");
            DWObject.SetHTTPFormField('_token', token);
        }

        function loadImage() {
            var OnSuccess = function() {};
            var OnFailure = function(errorCode, errorString) {};

            if (DWObject) {
                DWObject.IfShowFileDialog = true;
                DWObject.LoadImageEx("", EnumDWT_ImageType.IT_ALL, OnSuccess, OnFailure);
            }
        }

        function acquireImage() {
            if (DWObject) {
                DWObject.IfShowUI = false;
                DWObject.IfDisableSourceAfterAcquire = true; 
                DWObject.SelectSource(); 
                DWObject.OpenSource
                DWObject.AcquireImage();
            }
        }

        function upload() {
            var OnSuccess = function(httpResponse) {
                alert("Succesfully uploaded");
            };

            var OnFailure = function(errorCode, errorString, httpResponse) {
                alert(httpResponse);
            };

            var date = new Date();
            DWObject.HTTPUploadThroughPostEx(
                "{{ route('dwtupload.upload') }}",
                DWObject.CurrentImageIndexInBuffer,
                '',
                date.getTime() + ".jpg",
                1, // JPEG
                OnSuccess, OnFailure
            );
        }
    </script>

</body>

</html>

Routes

Add routes to routes\web.php:

Route::get('/dwt_upload', 'DWTUploadController@page');

Route::post('/dwt_upload/upload', 'DWTUploadController@upload')->name('dwtupload.upload');

Run the web server:

php artisan serve

Open http://127.0.0.1:8000/dwt_upload in your web browser.

Laravel web document scan

Why Error Code?

419 status code

If you do not set CSRF token in header, you will fail to send the post request and get the 419 status code.

Laravel CSRF

500 status code

You may get the exception “Symfony\Component\Mime\Exception\LogicException: Unable to guess the MIME type as no guessers are available (have you enable the php_fileinfo extension?)

Laravel php fileinfo extension

The workaround is to enable “extension=fileinfo” in the php.ini file.

php int extension

Reference

https://laravel.com/docs/5.8

Source Code

https://github.com/dynamsoft-dwt/laravel-web-document-scan

 

The post Uploading Scanned Documents in Windows 10 Laravel Project appeared first on Code Pool.


Viewing all articles
Browse latest Browse all 239

Trending Articles