<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" onchange="uploadFileGoogleDrive(event)">
<div class="progress">0%</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function uploadFileGoogleDrive(event) {
let file= event.target.files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function (e) {
let multipart =
`
--foo
Content-Type: application/json; charset=UTF-8
{
"name": "${file.name}"
}
--foo
Content-Transfer-Encoding: base64
${btoa(reader.result)}
--foo--`;
let ajax = $.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=*',
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
let percentComplete = (evt.loaded / evt.total) * 100;
$('.progress').text(percentComplete + '%');
}
}, false);
return xhr;
},
headers: {
"Authorization": "Bearer <token>",
"Content-Type": "multipart/related; boundary=foo",
},
type: 'POST',
data: multipart,
success: function (result, textStatus, xhr) {
if (xhr.status == 200) {
console.log(result);
}
},
error: function (results) {
}
});
}
}
</script>
</body>
</html>