Building a Form with file upload

It's little trickier, but nothing you can't handle!

Working with files

If you've read the tutorial on building a simple Form, you can see that it's easily modifiable to have as many information fields as you want it to have. Text, numbers, you name it: just add the input fields and it should work just fine!

However, when dealing with files, things can get a little bit tricky. It's necessary to convert the uploaded file to a Base64 format before sending it to the back-end function.

In this example, we'll show you how to do just that.

Building the app

We're going to increment the form we build on the previous tutorial, so if you haven't read it yet, it's a good idea to check it out (it's super quick).

So, we'll start by creating a new picture field on the Companies table. We'll call it Logo. Then, we'll modify the page to have an input field of the type file, so users can upload a picture from their computer.

1552
{{ Jestor.addJS('submitform') }}

<input type="text" id="name" label="Name">
<input type="file" id="file" label="File"> 
<button id="submit">Submit</button>
<br><br><span id="company_created"></span>

Now, we're going to modify the Javascript function with two additions:

  1. We're going to create a function to encode the file as Base64.
  2. We're going to send this inside the JSON of parameters to the standard function.
1552
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
      });
    }


$(document).ready(function(){
    $('#submit').click(function(){
        getBase64($('#file')[0].files[0]).then(
            (data) => {
                callFunction("createcompany",{company_name:$('#name').val(),company_file:data},'company_created',true);
            }
        );
    });
});

Now, we're going to modify the standard function CreateCompany to decode this Base64 string and create the file inside Jestor, so we can attribute it to the picture field. We're exploding the string as everything before the "," is regarding the data type, and not the encoded file itself.

1552
$base64 = explode(',',$data['company_file']);
$decodedb64 = base64_decode($base64[1]);
$createdfile = Jestor.createNewFile($decodedb64,"png");

$company = Jestor.create('companies',['name' => $data['company_name'],'logo' => $createdfile]);
$message = $company['name']." was created as a company with id = ".$company['id_companies'];
{{ $message }}

And it's done! Let's see this in action:

800

There you go! We successfully created a record with the uploaded company logo! 🥳