gpt4 book ai didi

javascript - 将文件夹上传到 GDrive 并获取用于上传文件的文件夹 ID

转载 作者:行者123 更新时间:2023-12-04 09:28:05 29 4
gpt4 key购买 nike

感谢阅读我的问题。我正在研究 google drive api,可以将文件从文本 blob 上传到 google drive。但是,我需要手动添加文件夹 ID,以便用户在尝试将其上传到我的 文件夹时使用它而不会出现错误。我如何创建或只获取文件夹 ID - 甚至可能上传到根 GDrive 目录?任何提示都会有所帮助。

谢谢

// Global vars
const SCOPE = 'https://www.googleapis.com/auth/drive.file';
const gdResponse = document.querySelector('#response');
const login = document.querySelector('#login');
const authStatus = document.querySelector('#auth-status');
const textWrap = document.querySelector('.textWrapper');
const addFolder = document.querySelector('#createFolder');
const uploadBtn = document.querySelector('#uploadFile');

// Save Button and Function
uploadBtn.addEventListener('click', uploadFile);

window.addEventListener('load', () => {
console.log('Loading init when page loads');
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
});

function initClient() {
const discoveryUrl =
'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';

// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client
.init({
apiKey: 'My-API-Key',
clientId:
'My-Client-ID',
discoveryDocs: [discoveryUrl],
scope: SCOPE,
})
.then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();

// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);


// Actual upload of the file to GDrive
function uploadFile() {
let accessToken = gapi.auth.getToken().access_token; // Google Drive API Access Token
console.log('Upload Blob - Access Token: ' + accessToken);

let fileContent = document.querySelector('#content').value; // As a sample, upload a text file.
console.log('File Should Contain : ' + fileContent);
let file = new Blob([fileContent], { type: 'application/pdf' });
let metadata = {
name: 'Background Sync ' + date, // Filename
mimeType: 'text/plain', // mimeType at Google Drive

// For Testing Purpose you can change this File ID to a folder in your Google Drive
parents: ['Manually-entered-Folder-ID'], // Folder ID in Google Drive
// I'd like to have this automatically filled with a users folder ID
};

let form = new FormData();
form.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
form.append('file', file);

let xhr = new XMLHttpRequest();
xhr.open(
'post',
'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'
);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(
'Upload Successful to GDrive: File ID Returned - ' + xhr.response.id
); // Retrieve uploaded file ID.
gdResponse.innerHTML =
'Uploaded File. File Response ID : ' + xhr.response.id;
};
xhr.send(form);
}

我没有包括一些不相关的东西。我有类似的东西用于上传文件夹,但不出所料,它无法正常工作。

function createFolder() {
var fileMetadata = {
name: 'WordQ-Backups',
mimeType: 'application/vnd.google-apps.folder',
};
drive.files.create(
{
resource: fileMetadata,
fields: 'id',
},
function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('Folder Id: ', file.id);
}
}
);
}

最佳答案

我相信你的目标如下。

  • 您想将文件上传到根文件夹或创建的新文件夹。

为此,下面的修改模式怎么样?

模式一:

当你想把文件放到根文件夹时,请尝试如下修改。

来自:

parents: ['Manually-entered-Folder-ID'],

收件人:

parents: ['root'],

或者,请删除 parents: ['Manually-entered-Folder-ID'],。这样,文件就创建到了根文件夹。

模式二:

当你想创建新文件夹并将文件放入创建的文件夹时,请尝试以下修改。不幸的是,在您的脚本中,我不确定您问题中 createFolder() 中的 drive 。所以我无法理解您的 createFolder() 问题。因此,在此模式中,文件夹是使用 XMLHttpRequest 创建的。

修改后的脚本:

function createFile(accessToken, folderId) {
console.log('File Should Contain : ' + fileContent);
let fileContent = document.querySelector('#content').value;
console.log('File Should Contain : ' + fileContent);
let file = new Blob([fileContent], { type: 'application/pdf' });

let metadata = {
name: 'Background Sync ' + date,
mimeType: 'text/plain',
parents: [folderId], // <--- Modified
};
let form = new FormData();
form.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
form.append('file', file);

let xhr = new XMLHttpRequest();
xhr.open(
'post',
'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'
);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(
'Upload Successful to GDrive: File ID Returned - ' + xhr.response.id
);
gdResponse.innerHTML =
'Uploaded File. File Response ID : ' + xhr.response.id;
};
xhr.send(form);
}

function createFolder(accessToken) {
const folderName = "sample"; // <--- Please set the folder name.

let metadata = {
name: folderName,
mimeType: 'application/vnd.google-apps.folder'
};
let xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/drive/v3/files?fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = () => {
const folderId = xhr.response.id;
console.log(folderId);
createFile(accessToken, folderId);
};
xhr.send(JSON.stringify(metadata));
}

// At first, this function is run.
function uploadFile() {
let accessToken = gapi.auth.getToken().access_token;
createFolder(accessToken);
}

引用:

关于javascript - 将文件夹上传到 GDrive 并获取用于上传文件的文件夹 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62940637/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com