Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving binary string to file in php sent from POST

I have a drag and drop uploader for (.jpg,.ai,.pdf,.flv,.psd ....etc.)

I'm reading the file as binary and sending the string in a jquery post:

function importZoneDrop(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files; // FileList object.

    // files is a FileList of File objects. List some properties.
    for (var i = 0, f; f = files[i]; i++) {
        var start = 0;
        var stop = files[0].size - 1;
        var reader1 = new FileReader();
        var reader2 = new FileReader();
        var ext = f.name.substring(f.name.indexOf(".")+1);
        if(ext == "JPEG" || ext == "jpeg" || ext == "JPG"){
            ext ="jpg";
        }

        reader1.onload = (function(theFile) {
            return function(e) {
              // Render thumbnail.
              $("#import-drop-zone").append('<img src="'+e.target.result+'" />');
            };
         })(f);

        reader2.onloadend = function(evt) {
          if (evt.target.readyState == FileReader.DONE) { // DONE == 2
            $.post("/process/upload.php",{"blob":evt.target.result,"extension":ext},function(data){
                console.log(data);
            });
          }
        };

        reader1.readAsDataURL(f);
        var blob = f.slice(start, stop + 1);
        reader2.readAsBinaryString(f);
    }
  }

This works and send the file. Next Get the string and write it using file_put_contents:

$extension = $_POST['extension'];
$file = $_POST['blob'];//sent from jquery post
$filePath = "../_temp/monkey.".$extension;

file_put_contents($filePath,$file);
if(file_put_contents($filePath,$file)){
    echo json_encode("it worked");
}else{
    echo json_encode("it failed");
}

This will successfully write the file. But the file does not work, it's broke.

What am I doing wrong?

like image 316
Jason Spick Avatar asked Oct 21 '25 18:10

Jason Spick


1 Answers

You need to use base64_decode.

file_put_contents($filePath, base64_decode($file));

Note, you're currently writing the data twice. Don't.

if (file_put_contents($filePath, base64_decode($file))) {

is fine

Edit

Also worth nothing that it's more efficient to upload the binary file directly, then you can skip base64_decode. Something like this:

var xhr  = new XMLHttpRequest(),
    data = new FormData();

data.append("file", f); // You don't need to use a FileReader
// append your post fields

// attach your events
xhr.addEventListener('load', function(e) {});
xhr.upload.addEventListener('progress', function(e) {});

xhr.open('POST', '/process/upload.php', true);
xhr.send(data);

You can view the rest of the events here with some samples here.

like image 79
Martin Avatar answered Oct 23 '25 08:10

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!