Cordova for android 中的 XMLHttpRequest

问题描述 投票:0回答:2

我实际上遇到了一个问题。在 Cordova 中为 Android 构建应用程序。我需要从服务器中的变量路径下载 PDF。 Cordova 的文档说“从 cordova-plugin-file-transfer 中过渡”,位于 here ,我尝试了以下操作:

 var oReq = new XMLHttpRequest();
        // Make sure you add the domain name to the Content-Security-Policy <meta> element.
        oReq.open("GET", endereco, true);
        // Define how you want the XHR data to come back
        oReq.responseType = "blob";
        oReq.onload = function (oEvent) {
          var blob = oReq.response; // Note: not oReq.responseText
          if (blob) {
              console.log("WORKS??");
          } else console.error('we didnt get an XHR response!');
        };
        oReq.send(null);

其中“endereco”是一个变量,我在其中存储pdf路径。所以,我正在测试和测试,但也许有人得到了一些关于如何实现这一点的指示。现在它只记录“WORKS??”,所以我实际上连接成功了。但现在怎么办?

1 - 那么,我提出了请求,但文件已保存?我的手机里找不到任何东西。如何将所述 blob 保存在与服务器具有相同名称和扩展名的文件夹中?

因此,如果有人至少可以向我发送一些正确的示例或文档,那将会有很大帮助。现在我正在阅读 MDN Web Docs 上的所有内容,但我对这种类型的代码相当菜鸟:(

提前致谢!

android cordova request
2个回答
1
投票

所以,这对我来说就是这样的!使用cordova官方文档中的信息,以前名为“cordova-plugin-file”(link),以及此页面中的令人惊叹的信息以及示例“CORDOVA文件插件示例”(link),它起作用了。它可以使用一些清理和一些错误回调,但现在我可以运行它,并将 pdf 下载并保存到我的 android 中。希望它能帮助别人! B-)

  document.addEventListener('deviceready', onDeviceReady, false);  

函数 onDeviceReady() { var 文件地址;

var req = new XMLHttpRequest();
req.open("GET", endereco, true);
req.responseType = "blob";

req.onload = function (event) {
  var blob = req.response;
  console.log(blob.size);
  console.log(blob.type);
  console.log("WORKS!");
  console.log(fileURL);          

  // cordova.file.etc is where you will save the file. In this case, inside the app folder, in the main storage in Android
  window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
    // the 'temp.pdf' is the name you want for your file.
    directoryEntry.getFile('temp.pdf', { create: true }, function (fileEntry) {
      fileEntry.createWriter(function (fileWriter) {
        fileWriter.onwriteend = function (e) {
          // great success!
          console.log('Write of file completed.');
        };

        fileWriter.onerror = function (e) {
          // Meh - fail
          console.log('Write failed');
        };

        fileWriter.write(blob);
      } );
    } );
  });
};

req.send();}

0
投票

此代码不适用于大文件:(

© www.soinside.com 2019 - 2024. All rights reserved.