使用Apps Script转PDF遇Drive.Files.insert不存在错误求助
解决TypeError: Drive.Files.insert is not a function的问题
问题原因
你调用的Drive.Files.insert是Google Drive API v2的专属方法,但当前Apps Script中启用的Advanced Drive API默认是v3版本,v3已移除该方法并替换为Drive.Files.create,这就是报错的核心原因。
修复步骤
替换API方法并调整参数
Drive API v3不仅更换了方法名,还调整了字段命名(比如title改为name)和参数结构,修复后的完整代码如下:/* * Convert PDF file to text * @param {string} fileId - The Google Drive ID of the PDF * @param {string} language - The language of the PDF text to use for OCR * return {string} - The extracted text of the PDF file */ const convertPDFToText = (fileId, language) => { fileId = fileId || '18FaqtRcgCozTi0IyQFQbIvdgqaO_UpjW'; // Sample PDF file language = language || 'en'; // English // Read the PDF file in Google Drive const pdfDocument = DriveApp.getFileById(fileId); // Use OCR to convert PDF to a temporary Google Document // Restrict the response to include file Id and Name fields only const { id, name } = Drive.Files.create( { name: pdfDocument.getName().replace(/\.pdf$/, ''), // v3用name替代原v2的title mimeType: 'application/vnd.google-apps.document', // 明确指定转换后的Google文档MIME类型 }, pdfDocument.getBlob(), { ocr: true, ocrLanguage: language, fields: 'id,name', // 对应v3返回字段 } ); // Use the Document API to extract text from the Google Document const textContent = DocumentApp.openById(id).getBody().getText(); // Delete the temporary Google Document since it is no longer needed DriveApp.getFileById(id).setTrashed(true); // (optional) Save the text content to another text file in Google Drive const textFile = DriveApp.createFile(`${name}.txt`, textContent, 'text/plain'); return textContent; };配置验证
如果替换后仍报错,检查以下配置项:- 确认已通过「扩展」→「Apps Script API」启用Apps Script API
- 确认Advanced Drive API已添加:点击编辑器左侧「服务」→「添加服务」→ 找到「Drive API」并完成添加(无需手动指定版本,默认v3即可)
内容的提问来源于stack exchange,提问作者Jim Burke
相关产品推荐
相关产品推荐

