Skip to main content

jQuery fileupload BlueImp base64 encoding before send

 https://github.com/blueimp/jQuery-File-Upload/issues/2924

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />

<div id="imgTest"></div>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script type='text/javascript'>

  function encodeImageFileAsURL() {


    var filesSelected = document.getElementById("inputFileToLoad").files;

    if (filesSelected.length > 0) {

      var fileToLoad = filesSelected[0];

      var fileReader = new FileReader();

      var srcData = null;

      fileReader.onload = function(fileLoadedEvent) {

        var srcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = document.createElement('img');

        newImage.src = srcData;

        document.getElementById("imgTest").innerHTML = newImage.outerHTML;

        // alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);

        console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);


        request = $.ajax({

          url: '/import_file/base64-api2.php',

          type: 'POST',

          // dataType: 'json',

          // encode: true,

          async: false,

          // contentType: 'application/json',

          // processData: false,

          // contentType: false,

          data: {"media":srcData}

          // data: JSON.stringify({})

        });

      }

      fileReader.readAsDataURL(fileToLoad);

      // Callback handler that will be called on success

      request.done(function (response, textStatus, jqXHR){

          // Log a message to the console

          console.log("Hooray, it worked!");

      });

      // Callback handler that will be called on failure

      request.fail(function (jqXHR, textStatus, errorThrown){

          // Log the error to the console

          console.error(

              "The following error occurred: "+

              textStatus, errorThrown

          );

      });

        // Callback handler that will be called regardless

      // if the request failed or succeeded

      request.always(function () {

          // Reenable the inputs

          // $inputs.prop("disabled", false);

      });

    }

  }

</script>


Chunk file for upload.

PHP decode

function base64_to_jpg($base64, $output_file) {

    $ext = 'jpeg';

    $img = str_replace('data:image/jpeg;base64,', '', $base64);

    $img = str_replace(' ', '+', $img);

    $data = base64_decode($img);

    $file = "./starbase/" . uniqid() . '.jpg';

    $success = file_put_contents($file, $data);

}


https://stackoverflow.com/questions/30107521/check-if-same-image-has-already-been-uploaded-by-comparing-base64

Base64 chunked

https://github.com/blueimp/jQuery-File-Upload/issues/1947


https://coderedirect.com/questions/659704/blueimp-file-upload-remove-a-file-from-file-list-before-upload


jsFiddle alike

http://jsbin.com/piqiqecuxo/1/edit?js,console,output

http://jsfiddle.net/ghinda/fRgbf/

https://github.com/blueimp/jQuery-File-Upload/pull/3052/files#diff-39a834a672a00c7e950ff109bc4342d6R1433

https://github.com/blueimp/jQuery-File-Upload/pull/3052


https://stackoverflow.com/questions/8668449/xmlhttprequest-vs-httprequest


https://github.com/blueimp/jQuery-File-Upload/issues/2606


What I need is preprocess the file be4 send.

https://stackoverflow.com/questions/20897896/jquery-file-upload-where-is-the-file-data-when-pre-processing-http-blueimp-gi



Update working example here both blueimp JS + API in PHP.

PHP UploadHandler seem not necessary ?

Fast notes:

- to encode and append base64 file data to POST:
inside fileupload() add: event, add:

try {
              async function convertFileToBase64(file) {

                    let base64Promise = new Promise((resolve, reject) => {

                      const reader = new FileReader();

                      reader.readAsDataURL(file[0]);

                      console.log('be4 onload');

                      reader.onload = () => {

                        data.fileBase64 = reader.result;

                        resolve(data.fileBase64);

                        data.submit();

                      };

                      reader.onerror = reject;

                    });

                    await base64Promise;

                }

                convertFileToBase64(data.files);

                // data.submit();

            } catch(err) {

                console.log(err);

            }

...

To append to formData:
in event chunkbeforesend (add new event if you not added yet). This is for split chunk big file.

chunkbeforesend: function (e, data) {

            data.formData = {

                'folderId': id_folder_selected,

                'uniqueFileName': uniqueFileName,

                'fileBase64': data.fileBase64,

                'fileType': data.files[0].type,

                'fileSize': data.files[0].size,

                'fileName': data.files[0].name

            };

        },

...

In case only 1 part (small file or not enable config split file):

add bind() method
fileupload(...).bind():

.bind('fileuploadsubmit', function (e, data) {

        // console.log(data.files);

        data.formData = {

            'folderId': id_folder_selected,

            'fileBase64': data.fileBase64,

            'fileType': data.files[0].type,

            'fileSize': data.files[0].size,

            'fileName': data.files[0].name

        };

    });


Disable file binary send:

inside _initXHRData, section near _isInstanceOf('Blob')...

// Do not send binary file to avoid blocked by CF...

// formData.append(

//   ($.type(options.paramName) === 'array' &&

//     options.paramName[index]) ||

//     paramName,

//   file, // file | null

//   fileName

// );

Do not send file in binary to avoid firewall scan for example SQLi BODY, in AWS WAF it scan first 8KB of body data (can be setting to more).

Server side (PHP), it seem we do not need UploadHandle.php or with simple server side handle (no image crop, resize...) => we can implement simple API to save base64 file. Be careful with another stuff like you have to escape filename yourself...

    public function base64Decode($base64, $type='')

    {

        if (empty($base64) || empty($type)) {
            return false;
        }

        $typeUrl = 'data:'. $type . ';base64,';

        $data = str_replace($typeUrl, '', $base64);

        $data = str_replace(' ', '+', $data);

        return base64_decode($data);

    }

    private function saveUploadedFile($data, $fileName, $path='')

    {

        $filePath = !empty($path) ? $fileName : $path . '/'. $fileName;

        $success = file_put_contents($filePath, $data);
        return $success;

    }

My code is lack of clean & refactoring so you should refactor yourself.


Don't know why merging chunk file on server side work without any change. Normally I have to using Content-Range header to merge programmatically.


https://github.com/puppeteer/puppeteer/issues/1599

Resource buffer size may be an issue when using base64 ? 

At least when debug data sent in Dev Tool.

https://stackoverflow.com/questions/27254735/filereader-onload-with-result-and-parameter

https://www.tabnine.com/code/javascript/functions/builtins/FileReader/onloadend

https://groups.google.com/a/dartlang.org/g/misc/c/-_89QH4IMU4

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/loadend_event

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

https://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue

https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example


https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript?rq=1


PHP base64_decode() 

base64_decode(string $string, bool $strict = false): string|false

strict

If the strict parameter is set to true then the base64_decode() function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.

To check base64 data, use crc32() check sum for verify same data.



Comments


  1. Croydon Cars MiniCab Service in London UK,Choose our Minicab

    for a quick trip and safely to get to the Gatwick Airport,

    Heathrow Airportalso offers some services to minicab drivers

    who are not associated with itin the area of Croydon and in

    other towns.We are offer Low Fair for Airport Transfers from

    Croydon everyday such as ✓Croydon Minicabs ✓Shirley Minicabs

    ✓Waddon Minicabsand etc.We want to welcome you to our new

    corporate website:www.croydoncar.co.uk/

    ReplyDelete

  2. Airport Transfer service from City Airport Taxis. Book your private airport transfers online, for a reliable transportation service at competitive, all inclusive prices.
    www.croydoncar.co.uk/

    ReplyDelete

Post a Comment

Popular posts from this blog

AWS Elasticache Memcached connection

https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/accessing-elasticache.html#access-from-outside-aws http://hourlyapps.blogspot.com/2010/06/examples-of-memcached-commands.html Access memcached https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/GettingStarted.AuthorizeAccess.html Zip include hidden file https://stackoverflow.com/questions/12493206/zip-including-hidden-files phpmemcachedadmin ~ phpMyAdmin or phpPgAdmin ... telnet mycachecluster.eaogs8.0001.usw2.cache.amazonaws.com 11211 stats items stats cachedump 27 100 https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/VPCs.EC.html https://lzone.de/cheat-sheet/memcached VPC ID Security Group ID (sg-...) Cluster: The identifier for the cluster memcached1 Creation Time: The time (UTC) when the cluster was created January 9, 2019 at 11:47:16 AM UTC+7 Configuration Endpoint: The configuration endpoint of the cluster memcached1.ahgofe.cfg.usw1.cache.amazonaws.com:11211 St...

Simulate Fail2ban on Apache request spam with mod_evasive limitipconn ...

https://en.wikipedia.org/wiki/Manchu_alphabet https://en.wikipedia.org/wiki/Sweet_potato https://en.wikipedia.org/wiki/New_World_crops https://www.mdpi.com/journal/energies http://www.cired.net/publications/cired2007/pdfs/CIRED2007_0342_paper.pdf https://www.davidpashley.com/articles/writing-robust-shell-scripts/ trap command https://en.wikipedia.org/wiki/Race_condition https://unix.stackexchange.com/questions/172541/why-does-exit-1-not-exit-the-script exit 1 not work it seem { } brace bound fixed it. cat access_log | cut -d ' ' -f 1 > ip1 sort -n -t. -k1,1 -k2,2 -k3,3 -k4,4 | uniq -c | sort -n -r -s https://unix.stackexchange.com/questions/246104/unix-count-unique-ip-addresses-sort-them-by-most-frequent-and-also-sort-them https://stackoverflow.com/questions/20164696/how-to-block-spam-and-spam-bots-for-good-with-htaccess  Code: ------------------------------------------------------------------- #Block Spam Bots and Spam on your website #Block proxies...

Notes Windows 10 Virtualbox config, PHP Storm Japanese, custom PHP, Apache build, Postgresql

 cmd => Ctrl + Shift + Enter mklink "C:\Users\HauNT\Videos\host3" "C:\Windows\System32\drivers\etc\hosts" https://www.quora.com/How-to-create-a-router-in-php https://serverfault.com/questions/225155/virtualbox-how-to-set-up-networking-so-both-host-and-guest-can-access-internet 1 NAT + 1 host only config https://unix.stackexchange.com/questions/115464/how-to-properly-set-up-2-network-interfaces-in-centos-running-in-virtualbox DEVICE=eth0 TYPE=Ethernet #BOOTPROTO=dhcp BOOTPROTO=none #IPADDR=10.9.11.246 #PREFIX=24 #GATEWAY=10.9.11.1 #IPV4_FAILURE_FATAL=yes #HWADDR=08:00:27:CC:AC:AC ONBOOT=yes NAME="System eth0" [root@localhost www]# cat /etc/sysconfig/network-scripts/ifcfg-eth1 # Advanced Micro Devices, Inc. [AMD] 79c970 [PCnet32 LANCE] DEVICE=eth1 IPADDR=192.168.56.28 <= no eff => auto like DHCP #GATEWAY=192.168.56.1 #BOOTPROTO=dhcp BOOTPROTO=static <= no eff ONBOOT=yes HWADDR=08:00:27:b4:20:10 [root@localhost www]# ...