首页 > 解决方案 > 如何使用反应和节点将字符串作为文件上传到谷歌驱动器

问题描述

如何使用 react js 作为前端和 node js 作为后端从谷歌驱动器上传/读取文件。

这是我已经尝试过的:将字符串写入文本文件,然后上传到谷歌驱动器

是否可以使用 react 上传文件?

如果没有,那么我想从 react 发送一个字符串到节点,然后上传到谷歌驱动器

标签: javascriptnode.jsreactjs

解决方案


我尝试了以下方法并为我工作。(截至目前,我仅从前端(vueJS)上传文件)。我假设你有谷歌客户端 ID & 客户端密码 & 刷新 & 访问令牌。

注意::: 当用户上传任何文件时,我会将这些文件存储在我的谷歌驱动器中。每次不登录我的帐户时,我都会通过执行一些步骤并在不登录的情况下访问我的谷歌驱动器来获取 access_token(不需要 OAuth。)。

前端代码VueJs(所有框架的html代码都相同)你必须通过输入获取文件上传代码,反应几乎与此类似

data:{
   file:''
}

<label>Files
    <input type="file" id="files" ref="file"  v-on:change="handleFilesUpload()"/> // here you can write corresponding react code for file uploading
  </label>
  <button v-on:click="submitFiles()">Submit</button>

**关于提交方法**

handleFilesUpload() {
        console.log("helloWorld");
        // this.files = this.$refs.files.files;
        this.file = this.$refs.file.files[0];
        console.log("file is ");
        console.log(this.file);
 }

  submitFiles() {
        // for storing file data
        let formData1 = new FormData();
        formData1.append('file',this.file); // here this.file is data when user browses through input button data will be stored to **file**

现在您将整个文件存储在formData1中。现在您必须通过 api 调用将此数据发送到 googledriveapi(我使用的是 axios)

API 调用

uploadFilesToGoogleDrive(formData1) {
     return axios({
        url:'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
        method:'post',
        headers:{
            'Content-Type': 'multipart/related;boundary=9700883396bond',
            'Authorization':'Bearer '+YOUR_ACCESS_TOKEN

        },

        formData1

    })
}

现在如果你去你的谷歌驱动器,你可以看到一个新创建的文件。以下链接可能会有所帮助。

上传到谷歌驱动器的示例脚本


推荐阅读