Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Last active February 20, 2023 06:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatsuyasusukida/5fcae93f75a5ccc0e43a1d6a86ef223c to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/5fcae93f75a5ccc0e43a1d6a86ef223c to your computer and use it in GitHub Desktop.
🏎 How to upload files to Google Drive without library
export default {
clientId: '000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Drive API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Drive API Quickstart</h1>
<button id="buttonSignin">Sign in</button>
<button id="buttonUpload">Upload</button>
<script type="module" src="main.mjs"></script>
</body>
</html>
import signin from "./signin.mjs"
import upload from "./upload.mjs"
import config from "./config.mjs"
main()
function main () {
const buttonSignin = document.querySelector('#buttonSignin')
const buttonUpload = document.querySelector('#buttonUpload')
const onClickButtonSignin = (event) => {
event.preventDefault()
signin(config)
}
const onClickButtonUpload = async (event) => {
event.preventDefault()
const {hash} = window.location
const pattern = /^#access_token=/
if (!pattern.test(hash)) {
return
}
const params = new URLSearchParams(hash.slice(1))
const accessToken = params.get('access_token')
const blob = new Blob(['test'], {
type: 'text/plain'
})
const response = await upload(accessToken, 'name', blob)
if (200 <= response.status && response.status < 300) {
console.log('OK')
}
}
buttonSignin.addEventListener('click', onClickButtonSignin)
buttonUpload.addEventListener('click', onClickButtonUpload)
}
{
"name": "google-drive-oauth2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "http-server -c-1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"http-server": "^14.1.1"
}
}
export default function signin ({clientId}) {
const endpoint = 'https://accounts.google.com/o/oauth2/v2/auth'
const search = '?' + new URLSearchParams({
client_id: clientId,
redirect_uri: 'http://localhost:8080/',
response_type: 'token',
scope: 'https://www.googleapis.com/auth/drive.file',
})
window.location.assign(endpoint + search)
}
export default async function upload (accessToken, name, file) {
const method = 'POST'
const url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'
const metadata = new Blob([JSON.stringify({name})], {
type: 'application/json; charset=UTF-8',
})
const formData = new FormData()
formData.append('Metadata', metadata)
formData.append('Media', file)
return await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${accessToken}`,
},
body: formData,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment