简体   繁体   中英

How do I encode (base64) a PDF file's blob using javascript and decode in PHP to save in SQL?

I have been trying for days now to build a file uploader using AJAX and PHP. I was able to upload images without any issue. But whenever it comes to PDF, I end up with blank pages.

Here is what I tried using FileReader:

for(const [key, file] of Object.entries($('input').prop('files'))){
  const reader = new FileReader()
  reader.onload = function(event){
    var object = {
      name:file.name,
      size:file.size,
      type:file.type,
      content:reader.result,
    }
    API.post("file/upload/?csrf="+CSRF,object,{
      success:function(result,status,xhr){
        console.log(result)
      }
    })
  }
  reader.readAsDataURL(file)
}

And in PHP:

// $_POST['content'] = base64_decode(str_replace('data:' . $_POST['type'] . ';base64,', '', $_POST['content']));
// $_POST['content'] = base64_decode($_POST['content']);
$_POST['content'] = base64_decode(urldecode($_POST['content']));

The results I got:

  • Uploading an images: Ok!
  • Uploading a single page PDF: PDF File only contains a blank page.
  • The results are the same using the 3 methods (readAsDataURL,readAsBinaryString,readAsText).
  • Using readAsText I keep getting: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Validated once saved in SQL using phpMyAdmin 5.

Expected results should be that any file type should be saved correctly.

NOTE: The API class is just a small class that includes parameters for $.post so I don't have to type them all the time.

First problem was that I was storing binary data in SQL which isn't meant for this type of use. This caused the SQL Database to corrupt the binary data.

Therefore, I redesign my file storage using locally stored Binary files (.bin) and SQL to provide all meta data of the files including the Path and more advanced ACL.

To secure the data, I use a rewrite rule RewriteRule ^data/.*$ - [F,L] . This prevents user from directly accessing the binary data. Therefore securing the file.

Once the changes made, I was able to save files through the application's API using the readAsDataURL method to retrieve the encoded binary data and send it over to the PHP API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM