Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I extract a zip file from a POST request?

I have a piece of client side code that exports a .docx file from Google Drive and sends the data to my server. It's pretty straight forward, it just exports the file, makes it into a blob, and sends the blob to a POST endpoint.

gapi.client.drive.files.export({
    fileId: file_id,
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
}).then(function (response) {

    // the zip file data is now in response.body
    var blob = new Blob([response.body], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});

    // send the blob to the server to extract
    var request = new XMLHttpRequest();
    request.open('POST', 'return-xml.php', true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.onload = function() {
        // the extracted data is in the request.responseText
        // do something with it
    };

    request.send(blob);
});

Here is my server side code to save this file onto my server so I can do things with it:

<?php
file_put_contents('tmp/document.docx', fopen('php://input', 'r'));

When I run this, the file is created on my server. However, I believe it is corrupted, because when I try to unzip it (as you can do with .docx), this happens:

$ mv tmp/document.docx tmp/document.zip
$ unzip tmp/document.zip
Archive:  document.zip
error [document.zip]:  missing 192760059 bytes in zipfile
  (attempting to process anyway)
error [document.zip]:  start of central directory not found;
  zipfile corrupt.
  (please check that you have transferred or created the zipfile in the
  appropriate BINARY mode and that you have compiled UnZip properly)

Why isn't it recognizing it as a proper .zip file?

like image 602
Lincoln Bergeson Avatar asked May 24 '17 21:05

Lincoln Bergeson


1 Answers

You should first download the original zip, and compare its content to that what yhou receive on you server, you can do this e.gg. with totalcommander or line "diff" command.

When you do this, you will see if your zip is change during transfer. With this information you can continue searching WHY it is changed. E.g. when in you zipfile ascii 10 is transformed to "13" or "10 13" it could be a line ending problem on the file transfer

Because when you open files in php with fopen(..., 'r') it can happen, that \n signs are transformed when you are using windows, you could try to use fopen(..., 'rb') wich enforces BINARY reading a file without transfering line endings.

@see: https://stackoverflow.com/a/7652022/2377961

@see php documentation fopen

like image 166
Radon8472 Avatar answered Oct 25 '22 18:10

Radon8472