Javascript 如何将字符串作为文件上传到Google Drive?
我的问题是: 我想创建一个GoogleSheets扩展,在这个扩展中,我基本上从GoogleSheets中的一个工作表中提取数据,并使用NodeJS中的方法对其进行修改。 然后,将我修改的数据放在一个字符串中,我想将该字符串以csv或xml文件的形式上传到客户机的驱动器中。因此,我没有可以用来上传文件的本地文件,只有一个字符串变量。 如何上传该字符串? 非常感谢,这是我的第一个应用,我有点挣扎 代码Javascript 如何将字符串作为文件上传到Google Drive?,javascript,node.js,json,vue.js,google-api-nodejs-client,Javascript,Node.js,Json,Vue.js,Google Api Nodejs Client,我的问题是: 我想创建一个GoogleSheets扩展,在这个扩展中,我基本上从GoogleSheets中的一个工作表中提取数据,并使用NodeJS中的方法对其进行修改。 然后,将我修改的数据放在一个字符串中,我想将该字符串以csv或xml文件的形式上传到客户机的驱动器中。因此,我没有可以用来上传文件的本地文件,只有一个字符串变量。 如何上传该字符串? 非常感谢,这是我的第一个应用,我有点挣扎 代码 您必须设置文件的元数据及其包含的数据(在这种情况下,MIME类型必须是text/csv),并且文
您必须设置文件的元数据及其包含的数据(在这种情况下,MIME类型必须是
text/csv
),并且文件正文将是一个简单的字符串。考虑到您已经执行了OAuth进程,并且具有要插入的字符串,此代码将帮助您:
module.exports.init = async function (){
// Before calling the API, build your own Drive service instance
// In the second argument, you must pass your own string message
const pro = await uploadSimpleString(drive, null);
console.log(pro);
}
uploadSimpleString = (drive, message) => {
// Set file metadata and data
message = message || 'This is a simple String nice to meet you';
const fileMetadata = {'name': 'uploadSimpleStringt.csv'};
const media = {
mimeType: 'text/csv',
body: message
};
// Return the Promise result after completing its task
return new Promise((resolve, reject) => {
try{
// Call Files: create endpoint
return drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
},(err, results) => {
// Result from the call
if(err) reject(`Drive error: ${err.message}`);
resolve(results);
})
} catch (error){
console.log(`There was a problem in the promise: ${error}`);
}
});
}
通知
要测试此代码,请使用以下命令在CLI中运行它:
node -e 'require("./index.js").init()'
其中,index.js
是文件名,init()
是主要函数
文件
更多信息,请检查这些链接,也考虑使用[谷歌驱动器API ]标签,这样有更多的机会得到帮助,因为更多的人将能够找到你的问题。
node -e 'require("./index.js").init()'