使用Javascript从Google云端硬盘下载后,文件无效

时间:2016-04-21 07:37:55

标签: javascript google-drive-api ngcordova

我制作的Ionic应用程序必须下载存储在用户Google Drive中的音频文件并将其存储在手机中。试图获取文件数据和文件在JavaScript中写入,但下载后该文件不起作用。

我尝试过的事情:

1。发送了GET请求并尝试写入响应文件并保存文件

 var access_token = gapi.auth.getToken().access_token;

 $http({
   method:'GET',
      url:'https://www.googleapis.com/drive/v3/files/0B1ieItpgbVf8TFM2cC1MRHozekU?alt=media',
  headers:{'Authorization':'Bearer ' + access_token}
 }).success(function(result){
        // console.log(result);
     $scope.writefile(result);  
 }) 

$scope.writefile = function(funcdata) {

$scope.fle = funcdata;

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

// Cordova is ready
//
function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("synksongs/sample6.mp3", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
    writer.onwriteend = function(evt) {
        console.log("Done Writing file");

    };
    writer.write($scope.fle);
}

function fail(error) {
    console.log(error.code);
}
}

虽然文件正在写入但我无法播放,但似乎已损坏或部分下载可能是!

2.tried使用它从驱动器中检索文件内容并写入" ResponseText"使用我的$ scope.write()函数访问该文件:

 downloadFile(resp,function(result){
     $scope.writefile(result.responseText);         
 });

 function downloadFile(file,callback) {
  if (file.downloadUrl) {
    file.downloadUrl = file.downloadUrl+'&alt=media';
    console.log(file.downloadUrl);

    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file.downloadUrl);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr);

    };
    xhr.onerror = function() {
      callback(null);

    };
    xhr.send();
  } else {

    callback(null);
  }
}

第3。使用ngcordova文件传输插件尝试但只下载了部分文件

$scope.printFile = function() {
  var fileId = '0B1ieItpgbVf8TFM2cC1MRHozekU';

  var access_token = gapi.auth.getToken().access_token;

  var request = gapi.client.drive.files.get({
    'fileId': fileId,
    'headers': {
         'Authorization': 'Bearer ' + access_token,          
     }
  });

  request.execute(function(resp) {

      // console.log(resp);
     $scope.donwloadurl = resp.webContentLink;


  });
}

$cordovaFileTransfer.download($scope.donwloadurl, targetPath, options, trustHosts)
  .then(function(result) {
    // Success!
  }, function(err) {
    // Error
  }, function (progress) {
    $timeout(function () {
      $scope.downloadProgress = (progress.loaded / progress.total) * 100;
    });
  });

任何人都可以帮我这个!谢谢!

0 个答案:

没有答案