I followed the whole steps from google and I got some codes that I found here to make, and so I'm trying to upload a file from a form to Google Drive using the API, and that's the code:
var importFiles = $('#files')[0].files;
const boundary = '--cloud';
const delimiter = "\r\n" + boundary + "\r\n";
const close_delim = "\r\n" + boundary + "--";
var metadata = {
'name': importFiles[0]["name"],
'mimeType': importFiles[0]["type"],
'parents': ['parent-id']
};
var multipartRequestBody =
delimiter +
'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify(metadata) + "\r\n" +
delimiter + "\r\n" +
'Content-Type: ' + importFiles[0]["type"] + "\r\n\r\n" +
importFiles[0] +
close_delim;
gapi.client.request({
'path': '/upload/drive/v3/files',
'method': 'POST',
'params': {
'uploadType': 'multipart'
},
'headers': {
'Authorization': 'Bearer ' + gapi.client.getToken()["access_token"],
'Content-Type': 'multipart/related; boundary="cloud"'
},
'body': multipartRequestBody
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Google receives the information, and creates the file, the problem is that seems the file isn't going to Google or I don't know, all I got it's just the Google File without content. When I try to make a sample upload, everything goes well.
I think that your script is almost correct. But it is required to modify a little.
'Content-Transfer-Encoding: base64\r\n\r\n' +
.var importFiles = $('#files')[0].files;
const boundary = '--cloud';
const delimiter = "\r\n" + boundary + "\r\n";
const close_delim = "\r\n" + boundary + "--";
var metadata = {
'name': importFiles[0]["name"],
'mimeType': importFiles[0]["type"],
'parents': ['parent-id']
};
var f = new FileReader(); // Added
f.onload = function(){ // Added
var multipartRequestBody =
delimiter +
'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + importFiles[0]["type"] + "\r\n" +
'Content-Transfer-Encoding: base64\r\n\r\n' + // Added
btoa(this.result) + // Modified
closeDelim;
gapi.client.request({
'path': '/upload/drive/v3/files',
'method': 'POST',
'params': {
'uploadType': 'multipart',
},
'headers': {
'Authorization': 'Bearer ' + gapi.client.getToken()["access_token"],
'Content-Type': 'multipart/related; boundary="cloud"',
},
'body': multipartRequestBody,
}).then(function(r) { // Added
console.log(r); // Added
}); // Added
};
f.readAsBinaryString(importFiles[0]); // Added. I think that you can also use readAsDataURL().
This modified script supposes as follows.