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

Viewed 1996

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?

5 Answers
Related