我需要使用 Google Drive API v3 將 .doc 或 .docx 檔案上傳到 Google Drive,然后也使用 Google Drive API v3 將其轉換,以便檔案的內容在我自己的 Web 應用程式中可讀和可編輯(托管在 node.js 中)。 js)。我曾嘗試使用 drive.files.copy 執行此操作,但是,我一直收到錯誤訊息:API 回傳錯誤:錯誤:不支持將上傳的內容轉換為請求的輸出型別。誰能幫我弄清楚如何做到這一點?任何幫助將不勝感激。謝謝!
這是我用于轉換的代碼,但是,它不起作用:
drive.files.list({
q: "mimeType = 'application/msword'"
pageSize: 100,
fields: 'nextPageToken, files(id, name)',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' err);
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.map((file) => {
let result = (file.name).substring(0, (file.name).indexOf('.'));
console.log(file);
console.log(`${file.name} (${file.id})`);
drive.files.copy(
{
fileId: file.id,
requestBody: {
name: result,
mimeType: 'application/vnd.google-apps.document'
}
},
(err, res) => {
if (err) return console.log("The API returned an error: " err);
console.log(res.data);
}
);
});
}else {
console.log('No files found.');
}
});
這是我用于上傳檔案的代碼:
const driveResponse = drive.files.create({
requestBody: {
name: filename,
mimeType: mimetype
},
media: {
mimeType: mimetype,
body: Buffer.from(data).toString()
}
});
driveResponse.then(data => {
if(data.status == 200)
res.redirect('/notes');
else
console.log("file not uploaded.");
}).catch(err => { throw new Error(err) })
uj5u.com熱心網友回復:
當我看到你上傳檔案的腳本時application/msword,我注意到了一個修改點。那么下面的修改呢?在這種情況下,需要轉換為流型別。
此外,我確認當我buffer.toString()作為 的正文進行測驗時media,上傳的檔案是無效檔案。
修改后的腳本:
const { Readable } = require("stream");
const stream = new Readable();
stream.push(Buffer.from(data));
stream.push(null);
const driveResponse = drive.files.create({
requestBody: {
name: filename,
},
media: {
body: stream
}
});
driveResponse.then(data => {
if(data.status == 200)
res.redirect('/notes');
else
console.log("file not uploaded.");
}).catch(err => { throw new Error(err) })
筆記:
- 這個修改后的腳本假設您的值
Buffer.from(data)是有效值作為application/msword。因此,如果 的值Buffer.from(data)無效application/msword,請再次檢查資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377436.html
