[英]Google Drive API can not upload file into specific folder
I have a unlimited storage google drive account from my school account, so I shared drive with my main google account, I want to use apis of google drive to upload video to that shared drive by an file input form.我的学校帐户有一个无限存储的谷歌驱动器帐户,所以我与我的主要谷歌帐户共享驱动器,我想使用谷歌驱动器的apis通过文件输入表单将视频上传到该共享驱动器。 This is where i want to store the file:这是我想存储文件的地方:
I use express
, googleapis
, multer
我使用express
, googleapis
, multer
And this is how I have done:这就是我所做的:
this is my credentials.json
:这是我的credentials.json
:
{
"web": {
"client_id": "607849031009-4gsgo99bbskgsou5676b59ievp4fadmb.apps.googleusercontent.com",
"project_id": "spiritual-aloe-296616",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "OOAA7s1zXEUZ-5KemIhzjt4G",
"redirect_uris": ["http://localhost:5000/google/callback"],
"javascript_origins": ["http://localhost:5000"]
}
}
I use express
to write server and multer to upload file to the server:我用express
写服务器,用multer把文件上传到服务器:
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const OAuth2Data = require('./credentials.json');
var name, pic;
const {google} = require('googleapis');
const app = express();
const CLIENT_ID = OAuth2Data.web.client_id;
const CLIENT_SECRET = OAuth2Data.web.client_secret;
const REDIRECT_URL = OAuth2Data.web.redirect_uris[0];
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URL
);
var authed = false;
// If modifying these scopes, delete token.json.
const SCOPES =
'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.profile';
app.set('view engine', 'ejs');
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './images');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '_' + file.originalname);
},
});
var upload = multer({
storage: Storage,
}).single('file'); //Field name and max count
app.get('/', (req, res) => {
if (!authed) {
// Generate an OAuth URL and redirect there
var url = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log(url);
res.render('index', {url: url});
} else {
var oauth2 = google.oauth2({
auth: oAuth2Client,
version: 'v2',
});
oauth2.userinfo.get(function (err, response) {
if (err) {
console.log(err);
} else {
console.log(response.data);
res.render('success', {
success: false,
});
}
});
}
});
app.post('/upload', (req, res) => {
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.end('Something went wrong');
} else {
console.log(req.file.path);
const drive = google.drive({version: 'v3', auth: oAuth2Client});
const fileMetadata = {
name: req.file.filename,
};
const media = {
mimeType: req.file.mimetype,
body: fs.createReadStream(req.file.path),
};
drive.files.create(
{
resource: fileMetadata,
media: media,
fields: 'id',
},
(err, file) => {
if (err) {
// Handle error
console.error(err);
} else {
fs.unlinkSync(req.file.path);
res.render('success', {name: name, pic: pic, success: true});
}
}
);
}
});
});
app.get('/logout', (req, res) => {
authed = false;
res.redirect('/');
});
app.get('/google/callback', function (req, res) {
const code = req.query.code;
if (code) {
// Get an access token based on our OAuth code
oAuth2Client.getToken(code, function (err, tokens) {
if (err) {
console.log('Error authenticating');
console.log(err);
} else {
console.log('Successfully authenticated');
console.log(tokens);
oAuth2Client.setCredentials(tokens);
authed = true;
res.redirect('/');
}
});
}
});
app.listen(5000, () => {
console.log('App is listening on Port 5000');
});
finally it works, but the thing is, it uploaded to the home page of my google drive account终于成功了,但问题是,它上传到了我的 Google Drive 帐户的主页
meanwhile, I want it saved in the shared-drive folder, sorry for my bad English, thank you for help me out, hope you have a good day and a blessed ThanksGiving :)同时,我希望将它保存在共享驱动器文件夹中,抱歉我的英语不好,谢谢您的帮助,希望您有美好的一天和感恩节:)
UPDATE更新
this is the url of the shared-drive: https://drive.google.com/drive/u/3/folders/0AKRMoXHA-b-NUk9PVA?fbclid=IwAR2je0Ip7xwsaX7ghqZ0F0JWYYjImyvG1BEnRK2DjCGvRKFg7THFX8
这是共享驱动器的网址: https://drive.google.com/drive/u/3/folders/0AKRMoXHA-b-NUk9PVA?fbclid=IwAR2je0Ip7xwsaX7ghqZ0F0JWYYjImyvG1BEnRK2DjCGvRKFg7THFX8
: https://drive.google.com/drive/u/3/folders/0AKRMoXHA-b-NUk9PVA?fbclid=IwAR2je0Ip7xwsaX7ghqZ0F0JWYYjImyvG1BEnRK2DjCGvRKFg7THFX8
one more thing is that how can i got the url of the file i have just uploaded?还有一件事是我如何获得我刚刚上传的文件的网址?
You can create files in a specific folder by adding "parents" property in the request body and set its value based on the folder's id.您可以通过在请求正文中添加“parents”属性并根据文件夹的 id 设置其值来在特定文件夹中创建文件。
Sample:样本:
folder_id = 'xxxxxxxxsamplefolderidxxxx'
file_metadata = {
'name': 'photo.jpg',
'parents': [folder_id]
}
In your code:在您的代码中:
const fileMetadata = {
name: req.file.filename,
parents: 'xxxxxxxxsamplefolderidxxxx'
};
It is also stated that if "parents" is not specified as part of a create request, the file will be placed directly in the user's My Drive folder.还指出,如果“父母”未指定为创建请求的一部分,则该文件将直接放置在用户的“我的驱动器”文件夹中。 If not specified as part of a copy request, the file will inherit any discoverable parents of the source file.如果未指定为复制请求的一部分,该文件将继承源文件的任何可发现的父文件。 Update requests must use the addParents and removeParents parameters to modify the parents list.更新请求必须使用 addParents 和 removeParents 参数来修改父列表。
Reference: https://developers.google.com/drive/api/v3/reference/files/create参考: https : //developers.google.com/drive/api/v3/reference/files/create
To get the folder id, you can get it from the folder's link in drives.google.com要获取文件夹ID,您可以从drives.google.com 中的文件夹链接中获取
Sample:样本:
https://drive.google.com/drive/folders/1234SampleFolderId https://drive.google.com/drive/folders/1234SampleFolderId
where Folder Id = 1234SampleFolderId其中文件夹 ID = 1234SampleFolderId
(Updated based on additional questions) (根据其他问题更新)
Note: Folder Id should start after 'folders/' and ends before '?'注意:文件夹 ID 应该在 'folders/' 之后开始并在 '?' 之前结束。
Example: folders/ HereIsTheFolderId ?fbclid=示例:文件夹/ HereIsTheFolderId ?fbclid=
Regarding the url of the file that was uploaded, successful file creation will return a Files Resource in the response body.关于上传文件的 url,成功的文件创建将在响应正文中返回一个 Files 资源。
File Resource Reference: https://developers.google.com/drive/api/v3/reference/files#resource文件资源参考: https : //developers.google.com/drive/api/v3/reference/files#resource
webContentLink -A link for downloading the content of the file in a browser. webContentLink - 用于在浏览器中下载文件内容的链接。
webViewLink -A link for opening the file in a relevant Google editor or viewer in a browser. webViewLink - 用于在相关 Google 编辑器或浏览器查看器中打开文件的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.