I’m trying to upload files using the Google Drive API but running into issues. When I upload a file, it gets created but shows up as empty with the name “Untitled” and mimeType “application/octet-stream” instead of keeping the original file properties.
Here’s my current code:
var documentData = {
name: selectedFiles[i].name,
parents: this.targetFolderId ? [this.targetFolderId] : []
}
var uploadMedia = {
mimeType: selectedFiles[i].type,
body: selectedFiles[i]
}
window.gapi.client.drive.files.create({
resource: documentData,
media: uploadMedia,
fields: 'id, name, mimeType, createdTime'
}).then(response => console.log(response))
The file appears in my Drive but it’s completely empty and doesn’t have the correct metadata. What am I doing wrong with the upload process?
Yeah, I’ve hit this bug too. Switch to uploadType=‘resumable’ instead of multipart - it’s way more reliable. Also check that selectedFiles[i].type isn’t empty or undefined, because Drive will just default to octet-stream if it is. Quick fix: console.log the file type before upload to see what’s actually getting sent.
Had this exact problem with Google Drive API last year. You’re passing the file object directly in the body, but the API needs the actual file content as a stream or blob. I fixed it by using FileReader to convert the file to base64 or reading it as an ArrayBuffer first. Also check you’re using the right upload endpoint - you need multipart upload for files with content, not simple upload. Set uploadType to ‘multipart’ in your request. Without that, the API thinks you’re only creating metadata, which is why you’re getting empty files with generic properties.
Your problem is how you’re handling the file data. The Google Drive API needs properly formatted file content, but you’re passing the raw File object - that won’t work with the client library. I’ve seen this before with the gapi client. It creates the file entry but dumps no actual content.
Ditch the gapi client for file uploads. Use fetch requests instead. First, read your file with FileReader.readAsArrayBuffer(), then send it as form data with multipart/related content type. The gapi client can’t handle binary data properly - that’s why you’re getting empty files.
Direct HTTP requests to the Drive API work way better for uploads, especially with larger files or specific mime types.