我正在尝试使用 Google Apps 脚本将 xlsx 文件从 Gmail 附件导入到 Google 云端硬盘(作为 Google 表格)。我尝试过在 GAS 中使用 Advanced Drive API,但这样做会导致以下错误:
对drive.files.insert 的API 调用失败并出现错误:无效的mime 类型
假如
我发现 Gmail 附件作为 application/octet 而不是 application/vnd.ms-excel 导入到 Google Apps 脚本中,我认为这是问题所在。但是,附件是一个 xlsx 文件,我不明白为什么它会被识别为应用程序/八位字节。
请记住,我想将 XLSX 转换为 Google 表格。因此我需要 MimeType。
这是代码:
var mail = GmailApp.search("XXXXXXX")[0];
var msg = mail.getMessages()[0]
var attachment = msg.getAttachments()[0];
var blob =attachment
var name = attachment.getName();
var folderId = 'XXXXXX';
var file = {
title: 'Converted Spreadsheet',
parents: [{id: folderId}],
mimeType: MimeType.GOOGLE_SHEETS
};
file = Drive.Files.insert(file, blob, {convert: true})
有谁知道如何修复错误或找到另一种方法将此 XLSX 转换为工作表?
谢谢!
- 在您的情况下,mimeType 为
blob
附件文件的内容是application/octet
.
-
blob
实际上是一个XLSX文件。
- When
blob
of application/octet
与使用Drive.Files.insert()
,误差为Invalid mime type provided
occurs.
- 您想要将上述 blob 的 XLSX 文件转换为 Google Spreadsheet 并将其创建为文件。
- 您希望使用 Google Apps 脚本来实现此目的。
如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。
问题和解决方法:
- When the mimeType of
blob
is application/octet
,
- When
Drive.Files.insert({title: 'Converted Spreadsheet', parents: [{id: "root"}], mimeType: MimeType.GOOGLE_SHEETS}, blob, {convert: true})
运行时,错误为Invalid mime type provided
occurs.
- When
Drive.Files.insert({title: 'Converted Spreadsheet', parents: [{id: "root"}]}, blob, {convert: true})
运行,没有出现错误。但创建的文件的 mimeType 是application/octet
。这样,该文件就无法直接在 Google Drive 上打开。在这种情况下,需要将创建的文件的mimeType更改为XLSX。我认为这是由于This field can be left blank, and the mimetype will be determined from the uploaded content's MIME type.
. Ref https://developers.google.com/drive/api/v2/reference/files/insert#request-body
从上述情况来看,在这个答案中,我想建议将 XLSX 的 mimeType 设置为blob
before Drive.Files.insert
is run.
修改后的脚本:
当您的脚本修改时,请修改如下。
From:
var blob =attachment
To:
var blob = attachment.setContentType(MimeType.MICROSOFT_EXCEL); // MimeType.MICROSOFT_EXCEL or MimeType.MICROSOFT_EXCEL_LEGACY
or
To:
If blob
如果文件名带有扩展名,您还可以使用以下脚本。在这种情况下,mimeType 由文件名的扩展名自动给出。
var blob = attachment.setContentTypeFromExtension();
Note:
- 在上面修改的脚本中,有和没有的结果是相同的
mimeType: MimeType.GOOGLE_SHEETS
in file
.
- In your question, you say
an xlsx file from a Gmail Attachment
. And you say the Gmail attachment is imported to Google Apps Script as application/octet instead of application/vnd.ms-excel
.
- 如果文件是 XLSX 文件,则 mimeType 为
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.
- 如果 fie 是 XLS 文件,则 mimeType 为
application/vnd.ms-excel
.
参考:
- 设置内容类型(内容类型) https://developers.google.com/apps-script/reference/base/blob#setcontenttypecontenttype
- setContentTypeFromExtension() https://developers.google.com/apps-script/reference/base/blob#setcontenttypefromextension
- 枚举 MimeType https://developers.google.com/apps-script/reference/base/mime-type
如果这没有解决您的问题,我深表歉意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)