Reputation: 39
I did as in the documentation (https://developers.google.com/drive/api/v3/manage-uploads#http---single-request), but it doesn't work:
var fileMetadata = {
name: e.target.files[j].name,
parents: this.currentDirectoryId ? [this.currentDirectoryId] : []
}
var media = {
mimeType: e.target.files[j].type,
body: e.target.files[j]
}
window.gapi.client.drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id, name, mimeType, createdTime'
}).then(res => console.log(res))
File is created, but empty and named "Untitled" with mimeType "application/octet-stream"
Upvotes: 2
Views: 3116
Reputation: 201613
When I tested gapi.client.drive.files.create
, it seems that although this method can create new file with the metadata, the file content cannot be included. So in this answer, in order to upload a file by including the file metadata, I would like to propose to upload a file with multipart/form-data
using fetch
of Javascript. In this case, the access token is retrieved by gapi.auth.getToken().access_token
.
Unfortunately, from your script, I couldn't understand about e.target
. So in this sample script, I would like to propose the sample script for uploading a file, which is retrieved from the input tag, with the metadata.
<input type="file" id="files" name="file">
const files = document.getElementById("files").files;
const file = files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = (f) => {
const fileMetadata = {
name: file.name,
parents: this.currentDirectoryId ? [this.currentDirectoryId] : [] // This is from your script.
}
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
form.append('file', new Blob([new Uint8Array(f.target.result)], {type: file.type}));
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));
};
input
tag is uploaded to Google Drive with multipart/form-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: 2