Reputation: 35
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.
const img = await fetch("http://example.com/api/photo")
await gapi.client.drive.files.create({
resource: {
name: "New Folder",
body: img,
}
})
Upvotes: 1
Views: 2032
Reputation: 201593
I believe your goal as follows.
const img = await fetch("http://example.com/api/photo")
.fetch
, and the blob is uploaded to Google Drive.fetch
with 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
.http://example.com/api/photo
is the direct link of the image data.uploadType=multipart
. In this case, the maximum file size is 5 MB. Please be careful this. When you want to upload the file with the large size, please check the resumable upload. RefUpvotes: 1
Reputation: 117261
The simple anwser is you cant do it like that. The file being Uploaded must be sent in the form of a 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.
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);
}
});
Upvotes: 2