【发布时间】:2021-07-19 00:35:58
【问题描述】:
问题
我在 Google 云端硬盘上有一个文件,该文件是使用 Google 云端硬盘 api v3 上传的。 有问题的文件在上传时未转换为 Google 表格。 (是的,我的代码搞砸了,正在尝试修复它。)
它是用text/csv的mime类型上传的,下图显示它的类型为Comma separated values。
我有另一个文件以正确的 mime 类型 application/vnd.google-apps.spreadsheet 上传,这导致该文件被转换为 Google 表格。下图显示其类型为Google sheet
更新文件并修复它。
我要做的是对使用错误 mime 类型上传的文件运行 file.update,然后更改其 mime 类型并再次上传文件,从而将其转换为 Google 表格。
将以下内容作为文件的元数据发送应该会导致它被转换。
'mimeType': 'application/vnd.google-apps.spreadsheet'
不幸的是它不会导致以下错误
错误:[ { 域:'全球', 原因:'invalidContentType', message: '为上传的内容提供的 MIME 类型无效。', 位置类型:'其他', 位置:'media.mimeType' }
我的代码
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// npm install googleapis
// https://developers.google.com/drive/api/v3/quickstart/nodejs
// Desktop app credentials from Google Cloud console.
const KEYFILEPATH = 'C:\\Youtube\\dev\\ServiceAccountCred.json';
const FILEIDTOUPDATE = '1YtJxL1WptkHUbDHNWpcbKwcRs7rPo_cY';
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// Create a service account initialize with the service account key file and scope needed
const auth = new google.auth.GoogleAuth({
keyFile: KEYFILEPATH,
scopes: SCOPES
});
/**
* Creates a new file on google drive and uploads it.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
async function createAndUploadFile(auth) {
const driveService = google.drive({version: 'v3', auth});
let fileMetadata = {
'name': 'sheet',
'mimeType': 'application/vnd.google-apps.spreadsheet' // will cause the file to be converted to the google drive type.
};
let media = {
mimeType: 'text/csv',
body: fs.createReadStream('sheet.csv')
};
await driveService.files.update({
fileId : FILEIDTOUPDATE,
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.data.id);
}
});
}
createAndUploadFile(auth).catch(console.error);
我尝试过的。
为了测试这实际上不是我的代码的问题,我针对已正确上传的工作表运行了代码,并且工作正常。根据文档 MimeType 应该是可写的
我无法解释这个问题。我想知道 update 方法是否没有 create 方法的隐蔽超能力。
【问题讨论】:
-
感谢您的回复。我带来的不便表示歉意。从您对
While I understand your workaround, the documentation states mine type is write able so I should be able to update it. I already know about the copy method I am trying to use the update method.的回复中,我了解到我的回答对您的情况没有用处。我为我糟糕的技术深表歉意。所以我想删除我的答案。 -
@Tanaike 我希望你不要删除它,因为我确实认为它作为一种变通方法很有用。我将联系驱动团队中的某个人,看看这是否是文档中的错误。
-
感谢您的回复。从您的回复中,我重新打开了我的答案。如果这有用,我很高兴。
标签: node.js google-api google-drive-api service-accounts google-api-nodejs-client