使用Drive API v3的Apps Script移动文件报错:file.MoveTo不是函数
问题解决方法
错误原因
file对象类型不匹配:Drive.Files.create()返回的是Drive API v3的JSON响应对象,并非Google Apps Script中DriveApp的File实例,所以不存在MoveTo()方法。- 文件夹获取方式错误:
DriveApp.getFoldersByName()返回的是FolderIterator(文件夹迭代器),不是单个文件夹对象,直接传入方法会导致参数类型错误。
修正方案
方案1:创建文件时直接指定父目录(一步到位)
在创建文件的元数据里直接添加目标文件夹ID,文件会直接生成在目标路径下,无需后续移动:
function uploadfile() { try { // 获取目标文件夹,从迭代器中取出第一个匹配项 const folderIterator = DriveApp.getFoldersByName("Inbound CSV Files"); if (!folderIterator.hasNext()) { throw new Error("目标文件夹不存在"); } const targetFolder = folderIterator.next(); const csvf = UrlFetchApp.fetch('https://www.example.com/example.csv').getBlob(); const fileMetadata = { name: 'kev.csv', mimeType: 'text/csv', parents: [targetFolder.getId()] // 直接指定父目录 }; const file = Drive.Files.create(fileMetadata, csvf, {'fields': 'id,size'}); console.log('ID: %s, File size (bytes): %s', file.id, file.size); } catch (err){ console.log ('Failed to upload file with error %s', err.message); } }
方案2:先创建到根目录再移动
如果必须先将文件创建在根目录,再执行移动操作,可以将API返回的文件ID转为DriveApp的File实例,再调用moveTo()方法(注意方法名是小写m):
function uploadfile() { try { const folderIterator = DriveApp.getFoldersByName("Inbound CSV Files"); if (!folderIterator.hasNext()) { throw new Error("目标文件夹不存在"); } const targetFolder = folderIterator.next(); const csvf = UrlFetchApp.fetch('https://www.example.com/example.csv').getBlob(); const fileMetadata = { name: 'kev.csv', mimeType: 'text/csv' }; const file = Drive.Files.create(fileMetadata, csvf, {'fields': 'id,size'}); // 转换为DriveApp的File实例后执行移动 const driveFile = DriveApp.getFileById(file.id); driveFile.moveTo(targetFolder); console.log('ID: %s, File size (bytes): %s', file.id, file.size); } catch (err){ console.log ('Failed to upload file with error %s', err.message); } }
内容的提问来源于stack exchange,提问作者mtrack
相关产品推荐
相关产品推荐

