如何从Google Drive API下载/获取图像并将其呈现在我的Web应用程序上?

时间:2019-09-12 23:37:05

标签: javascript google-drive-api

我的任务是让用户登录自己的Google驱动器,选择图片,然后在我的Web应用程序上进行渲染。我可以将文件下载到本地计算机上,也可以在我的应用程序中查看和渲染缩略图(低质量)。但是,当我尝试渲染完整尺寸的图像时,没有收到CORS提示“访问控制允许原点”错误。

某些背景-正常工作和呈现的缩略图链接的域名中带有“ lh3”,而填充尺寸的图像的域名中带有“ drive.google”。我的同事建议使用一个快速端点来解决此问题(但我对express和Node.js不了解),而其他人则建议从Google驱动器api中获取该文件作为blob,然后将其下载到服务器上,然后从服务器连接到Web应用程序的前端。

class GoogleDrive {

    constructor () {
        this.thumbID = new Map();
    }

    startImport (choice, renderThumb) {
        gapi.load('client:auth2', this.initClient.bind(this, choice, renderThumb));
    }

    async initClient (choice, renderThumb) {
        const CLIENT_ID = '###';
        const API_KEY = '###';
        const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
        const SCOPES = 'https://www.googleapis.com/auth/drive';
        await gapi.client.init({
            apiKey: API_KEY,
            clientId: CLIENT_ID,
            discoveryDocs: DISCOVERY_DOCS,
            scope: SCOPES
        })

        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSigninStatus.bind(this, choice, renderThumb));

        // Handle the initial sign-in state.
        this.updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get(), choice, renderThumb);
    }

    updateSigninStatus (isSignedIn, choice, renderThumb) {
        if (isSignedIn) {
            this.getFiles(choice, renderThumb);
        } else {
            gapi.auth2.getAuthInstance().signIn();
        }
    }  

    handleSignOut () {
        gapi.auth2.getAuthInstance().signOut();
    }

    getFiles (choice, renderThumb) {
        let q = "";
        if (choice === 0) {
            q = "mimeType contains 'image/png'";
        } else {
            q = "mimeType = 'application/pdf'"
        } 
        gapi.client.drive.files.list({
            'pageSize': 10,
            'q':q,
            'fields': "files(id, name)"
        }).then(async (response) => {
            let files = response.result.files;
            if (files && files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    let file = files[i];;
                    let result = await gapi.client.drive.files.get({fileId: file.id, fields: '*'}); 
                    file.thumb = result.result.thumbnailLink;   
                    file.webView = result.result.webViewLink; 
                    this.thumbID.set(file.thumb, result.result);
                    renderThumb(file.thumb, file.webView, result.result.name);
                }
            } else {
                console.log('No files found.');
            }
        });
    }
}

module.exports = new GoogleDrive();

_onDrop (e) {
    eatEvent(e);
    let droppedFiles;
    if(e.dataTransfer.files.length){
      droppedFiles = e.dataTransfer.files;
    }else{
      droppedFiles = [e.dataTransfer.items[0].getAsString((url)=>
      {
        this.createBlob(url, e);
      })];
      return;
    }

  async createBlob (url, e){
    let result = GoogleDrive.thumbID.get(url);
    let file = await gapi.client.drive.files.get({
      fileId: result.id,
      alt: 'media'
    })
    this._processDroppedFiles(file, e.pageX, e.pageY);
   }

   _processDroppedFiles(droppedFiles, x = undefined, y = undefined) {
    if(DocumentData.isReadOnly) return;
    let files = droppedFiles;
    if (files.length === 0) {
      // show dialog: unsupported format
      System.emit(
        System.Types.SHOW_DIALOG,
        new ErrorDialog(
          ErrorDialog.ID.UPLOAD,
          f(Strings.UPLOAD_ERROR),
          f(Strings.UPLOAD_ONLY_IMAGES)
        )
      );
    } 
    else {
      System.emit(System.Types.START_LOADING);

      // only first file
      let firstFile = files;//[0];

        // a single image file
        this._uploadAndLoadImage(firstFile, firstFile.name)
        .then(obj => this._loadImage(obj, x, y))
        .then(()=> System.emit(System.Types.STOP_LOADING))
        .catch(e => {
          console.warn('upload failed');
          console.error(e);
          System.emit(System.Types.STOP_LOADING);
        });
      }     
    }
  }

0 个答案:

没有答案