为什么我不能从POST请求中提取zip文件?

Lin*_*son 8 javascript php zip docx google-drive-api

我有一段客户端代码,可以从Google云端硬盘导出.docx文件并将数据发送到我的服务器.它非常简单,它只是导出文件,使其成为blob,并将blob发送到POST端点.

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);
});
Run Code Online (Sandbox Code Playgroud)

这是我的服务器端代码,用于将此文件保存到我的服务器上,以便我可以使用它来执行操作:

<?php
file_put_contents('tmp/document.docx', fopen('php://input', 'r'));
Run Code Online (Sandbox Code Playgroud)

当我运行它时,该文件在我的服务器上创建.但是,我认为它已损坏,因为当我尝试解压缩它时(就像你可以用.docx做的那样),会发生这种情况:

$ 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)
Run Code Online (Sandbox Code Playgroud)

为什么不将它识别为正确的.zip文件?

Rad*_*472 5

你应该首先下载原始zip,并将其内容与你在服务器上收到的内容进行比较,你可以这样做e.gg. 使用totalcommander或行"diff"命令.

执行此操作时,您将看到在传输过程中是否更改了拉链.有了这些信息,您可以继续搜索它为何被更改.例如,当你在zipfile中ascii 10转换为"13"或"10 13"时,它可能是文件传输中的行结束问题

因为当你在php中打开文件fopen(..., 'r')时会发生这种情况,当你使用windows时会转换符号,你可以尝试使用fopen(..., 'rb')wich强制执行BINARY读取文件而不转移行结尾.

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

@see php文件fopen


小智 3

我认为这可能取决于“application/x-www-form-urlencoded”。因此,当您使用 php://input 读取请求数据时,它还会保存一些 http 属性,因此 .zip 已损坏。尝试打开 .zip 文件并查看里面的内容。要修复,如果问题是我之前所说的,请尝试将内容类型更改为应用程序/八位字节流。