后将文件上传到google驱动器"/>
http收到请求后将文件上传到google驱动器
我在单独的文件中具有两个功能,以拆分工作流程。
const download = function(url){
const file = fs.createWriteStream("./test.png");
const request = https.get(url, function(response) {
response.pipe(file);
});
}
我的fileHelper.js
中的此功能应该采用其中包含图像的URL,然后将其本地保存到test.png
中
function uploadFile(filePath) {
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), function (auth) {
const drive = google.drive({version: 'v3', auth});
const fileMetadata = {
'name': 'testphoto.png'
};
const media = {
mimeType: 'image/png',
body: fs.createReadStream(filePath)
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, (err, file) => {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
});
});
});
}
我的googleDriveHelper.js
中的此函数应该采用call的filePath,然后将该流上传到我的Google驱动器中。这两个函数可以独立工作,但是https.get似乎可以异步工作,如果下载后我尝试调用googleDriveHelper.uploadFile(filePath)
函数,则没有时间上传完整文件,因此空白文件将被上传到我的驱动器。
- 我想找到一种方法,当调用
fileHelper.download(url)
时,它会自动上传到我的驱动器中。 - 我也不知道是否有直接从
download
函数到upload
函数创建readStream的方法,因此我可以避免不得不在本地保存文件以上传它。
我相信您的目标如下。
- 您要将从URL检索的文件上传到Google云端硬盘。
- 从URL下载文件时,您希望将其上传到Google云端硬盘而不创建文件。
- 您想使用带有Node.js的googleapis实现此目的。
- 您已经能够使用Drive API上传文件。
为此,这个答案如何?
修改点:
- 在
download
函数中,将检索到的缓冲区转换为流类型,并返回流数据。 - 在
uploadFile
功能处,检索到的流数据用于上传。 - 从驱动器API的响应值中检索文件ID时,请使用
file.data.id
而不是file.id
。
通过上述修改,可以将从URL下载的文件上传到Google云端硬盘,而无需创建文件。
修改的脚本:
修改脚本后,请进行如下修改。
download()
const download = function (url) {
return new Promise(function (resolve, reject) {
request(
{
method: "GET",
url: url,
encoding: null,
},
(err, res, body) => {
if (err && res.statusCode != 200) {
reject(err);
return;
}
const stream = require("stream");
const bs = new stream.PassThrough();
bs.end(body);
resolve(bs);
}
);
});
};
uploadFile()
function uploadFile(data) { // <--- Modified
fs.readFile("drive_credentials.json", (err, content) => {
if (err) return console.log("Error loading client secret file:", err);
authorize(JSON.parse(content), function (auth) {
const drive = google.drive({ version: "v3", auth });
const fileMetadata = {
name: "testphoto.png",
};
const media = {
mimeType: "image/png",
body: data, // <--- Modified
};
drive.files.create(
{
resource: fileMetadata,
media: media,
fields: "id",
},
(err, file) => {
if (err) {
console.error(err);
} else {
console.log("File Id: ", file.data.id); // <--- Modified
}
}
);
});
});
}
用于测试
例如,当测试以上脚本时,以下脚本如何?
async function run() {
const url = "###";
const data = await fileHelper.download(url);
googleDriveHelper.uploadFile(data);
}
参考:
- Class: stream.PassThrough
- google-api-nodejs-client
更多推荐
http收到请求后将文件上传到google驱动器
发布评论