如何使用axios将文件上传到google drive API?我总是得到一个400错误

xnifntxz  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(133)

我试图上传一个文件到谷歌驱动器,我已经使用了刷新令牌,以获得新的访问令牌的每一个请求。如何使用axios设置请求
我已经根据链接https://developers.google.com/drive/api/v3/manage-uploads中的详细信息进行了设置

const data = new FormData();
data.append('mimeType', this.state.title);
data.append('name', `sermon-${Date.now()}.mp3`);
data.append('originalFilename', this.state.file.name);
data.append('parents[]', SERMON_FOLDER);
data.append('sermon', this.state.file);

Axios.post(`https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable`, data, {
              headers: {
                'Content-Type': 'application/json; charset=UTF-8',
                'Content-Length': this.state.file.size,
                Authorization: `Bearer ${response.data.token}`
              },
              onUploadProgress: (progressEvent) => {
                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                this.setState({ progress: percentCompleted });
              }
            })
              .then(response => {
                console.log(response.data)
                this.setState({ isLoading: false });
                ToastAndroid.show('Upload Successful, Your Sermon has been uploaded', 2500);
                this.props.navigation.navigate('Admin');
              }).catch(error => {
                console.log(error);
                this.setState({ isLoading: false });
                ToastAndroid.show('Connection Error', 3000)
              });

字符串
我希望得到一个响应,但实际的响应是来自服务器的400错误请求。

k97glaaz

k97glaaz1#

根据Google-API的要求,您需要以文件格式发送元数据

const formData = new FormData();
formData.append(
  "metadata",
  new Blob([JSON.stringify({ name: file.name, mimeType: "audio/*", parents: [ROOT_FOLDER_ID] })], {
    type: "application/json",
  }),
);
formData.append("file", file);

字符串

相关问题