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

Rand mm 10

https://stackoverflow.com/questions/2447791/define-vs-const Oh const vs define, many time I got unexpected interview question. As this one, I do not know much or try to study this. My work flow, and I believe of many programmer is that search topic only when we have task or job to tackle. We ignore many 'basic', 'fundamental' documents, RTFM is boring. So I think it is a trade off between the two way of study language. And I think there are a bridge or balanced way to extract both advantage of two method. There are some huge issue with programmer like me that prevent we master some technique that take only little time if doing properly. For example, some Red Hat certificate program, lesson, course that I have learned during Collage gave our exceptional useful when it cover almost all topic while working with Linux. I remember it called something like RHEL (RedHat Enterprise Linux) Certificate... I think there are many tons of documents, guide n books about Linux bu

Martin Fowler - Software Architecture - Making Architecture matter

  https://martinfowler.com/architecture/ One can appreciate the point of this presentation when one's sense of code smell is trained, functional and utilized. Those controlling the budget as well as developer leads should understand the design stamina hypothesis, so that the appropriate focus and priority is given to internal quality - otherwise pay a high price soon. Andrew Farrell 8 months ago I love that he was able to give an important lesson on the “How?” of software architecture at the very end: delegate decisions to those with the time to focus on them. Very nice and straight-forward talk about the value of software architecture For me, architecture is the distribution of complexity in a system. And also, how subsystems communicate with each other. A battle between craftmanship and the economics and economics always win... https://hackernoon.com/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011 1. Independent of Frameworks 2. Testable 3. Indepe