[英]How can I upload files to google drive that are in a url?
I try to upload a photo that I have in a URL on another server, but it does not work for me or I do not know how to upload them in this case I am going to upload a photo but I also want to upload files that will upload to that URL.我尝试在另一台服务器上上传我在 URL 中的照片,但它对我不起作用或者我不知道如何在这种情况下上传它们我要上传照片但我也想上传文件将上传到该 URL。
const img = await fetch("http://example.com/api/photo")
await gapi.client.drive.files.create({
resource: {
name: "New Folder",
body: img,
}
})
The simple anwser is you cant do it like that.简单的答案是你不能那样做。 The file being Uploaded must be sent in the form of a stream上传的文件必须以 stream 的形式发送
Download the file to your own machine and then upload it from there.将文件下载到您自己的机器上,然后从那里上传。 Or try to figure out how to turn your url into a stream.或者尝试弄清楚如何将您的 url 变成 stream。
var fileMetadata = {
'name': 'photo.jpg'
};
var media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('files/photo.jpg')
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
});
I believe your goal as follows.我相信你的目标如下。
const img = await fetch("http://example.com/api/photo")
.从您的脚本中,图像数据由const img = await fetch("http://example.com/api/photo")
下载。fetch
, and the blob is uploaded to Google Drive.在这种情况下,它从fetch
中检索 Blob 图像数据,并将该 Blob 上传到 Google Drive。fetch
with multipart/form-data
.下载的图像数据使用fetch
和multipart/form-data
上传。When above poiints are reflected to your script, it becomes as follows.当以上几点反映到您的脚本时,它变成如下。
const img = await fetch("http://example.com/api/photo").then((e) => e.blob());
const fileMetadata = {name: "sampleName"}; // Please set filename.
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
form.append('file', img);
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST',
headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
body: form
}).then(res => res.json()).then(res => console.log(res));
multipart/form-data
.通过此修改,下载的图像数据通过multipart/form-data
上传到 Google Drive。http://example.com/api/photo
is the direct link of the image data.您的http://example.com/api/photo
的 URL 是图片数据的直接链接。uploadType=multipart
.在此答案中,作为示例脚本,文件使用uploadType=multipart
上传。 In this case, the maximum file size is 5 MB.在这种情况下,最大文件大小为 5 MB。 Please be careful this.请注意这一点。 When you want to upload the file with the large size, please check the resumable upload.当您要上传大尺寸文件时,请勾选可续传。 Ref 参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.