0

I am trying to upload a blob which is a zip file, generated by JSZip(). Following code works perfectly fine if I put text (as a 'filedata') instead of blob (zip data). If I try to upload a zipped blob, I always get this error "filedata does not exists!". I don't think I miss any post on google to fix this issue, but nothing works. I have enough PHP upload limit, so that's not a problem. Even if I try to upload a zipped image in kb size, it doesn't work.

I am using NodeJs and VSCode. I would really appreciate the solution. Thank you.

Client-side (Javascript):

const req = new XMLHttpRequest();
req.responseType = 'blob';
const formData = new FormData();
formData.append('filename', fileName);
formData.append('filedata', blob, fileName);
req.open(
'POST',
'xyz.com/data/savedata.php',
true
);
req.upload.onprogress = function(e) {
if (e.lengthComputable) {
  const percentComplete = (e.loaded / e.total) * 100;
  console.log(percentComplete);
}
};

req.send(formData);

Server-side (savedata.php):

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    $filename = $_POST['filename'];
    $filedata = $_POST['filedata'];
    
    $dataTime = date("Y-m-d h:m:s");
    
    if ( isset($_POST['filename']) ) {
        error_log ("$dataTime  FileName '$filename' exists!\n", 3, 'logs.txt');
    } else {
        $filename = "DataFile.zip";
        error_log ("$dataTime  FileName does not exists! A New name is created.\n", 3, 'logs.txt');
    }
    
    if ( isset($_POST['filedata']) ) {
        error_log ("$dataTime  File data exists!\n", 3, 'logs.txt');
    
        $file = fopen($filename, 'wb');
        
        if ($file !== false) {
            if (fwrite($file, $filedata)) {
                error_log ("$dataTime  File has been written successfully!\n", 3, 'logs.txt');
                fclose($file);
            }
        } else {
            error_log ("$dataTime  Could not open '$filename' file!\n", 3, 'logs.txt');
        }
    } else {
        error_log ("$dataTime  filedata does not exists!\n", 3, 'logs.txt');
    }
?>
maxpayne
  • 1,111
  • 2
  • 21
  • 41

1 Answers1

0

I am not very good at PHP but i think it that you should access files using this:

if ( isset($_FILES['filedata'] ) {
   move_uploaded_file( $_FILES['userFile']['tmp_name'], "Desired Directory");
}

See this for more information