Загрузите файл с URL в Cordova и сохраните в android - PullRequest
0 голосов
/ 08 января 2020

Я использую Cordova fileopener2, чтобы открыть загруженный файл. На данный момент я тестирую с PDF-файлами. Мой URL-адрес возвращает PDF-файл. Я не уверен, является ли ответ большим двоичным объектом или потоком (есть ли способ узнать?), Но я сохраняю его, а затем открываю. Но когда я открываю его, оно пустое.

Это мой код:

await axios.get(fileLink.url)
      .then(res =>{

        if (Device.android || Device.ios){
          let blob = new Blob([res.data], {type: res.headers['content-type']});
          console.log(blob);

          let storageLocation = "";

          if (Device.android) {
              // console.log(cordova.file.externalDataDirectory);
              storageLocation = cordova.file.externalDataDirectory;
          } else if (Device.ios){
              // console.log(cordova.file.documentsDirectory);
              storageLocation = cordova.file.documentsDirectory;
          }

          window.resolveLocalFileSystemURL(
            storageLocation,
            function(dir) {
              dir.getFile(
                fileLink.name,
                {
                  create: true
                },
                function(file) {
                  file.createWriter(
                    function (fileWriter) {

                      fileWriter.write(blob);
                      console.log(file);

                      fileWriter.onwriteend = function () {

                        let url = file.toURL();
                        console.log(url);
                        cordova.plugins.fileOpener2.open(url, "application/pdf", {
                          error: function error(err) {
                            console.error(err);
                            alert("Unable to download 1");
                          },
                          success: function success() {
                            console.log("success with opening the file");
                          }
                        });
                      }

                      fileWriter.onerror = function(e){
                        console.log(e);
                      }

                    })
                },
                function(err) {
                  alert("Unable to download 2");
                  console.error(err);
                }
              );
            },
            function(err) {
              alert("Unable to download 3");
              console.error(err);
            }
          );

        } 
      })

Любая помощь приветствуется. Я уже искал много вопросов на форуме, но ни один не помог мне.

...