I need to upload a file from browser to my Google Drive. This is my upload code: (files
is an array of files get from <input type="file">
)
var boundary = "foo_bar_baz";
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var contentType = doc.mimeType;
var metadata = {
"title": doc.name,
"mimeType": doc.mimeType
};
var reader = new FileReader();
reader.onload = function(e){
var multipartRequestBody =
delimiter + 'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' +
e.target.result +
close_delim;
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart',
type: 'POST',
headers: {
"Authorization": 'Bearer ' + luminDriveAccessToken,
"Content-Type": 'multipart/related; boundary="'+ boundary + '"'
},
success: function() {
console.log('>>> Done uploading.');
},
error: _handleUploadErrors,
data: multipartRequestBody,
cache: false,
contentType: false,
processData: false,
crossDomain: true
});
};
reader.readAsBinaryString(files[0]);
When I run this script, the file got uploaded to my Google Drive (correct title, correct mimeType) but the file content is broken (Google Drive can't open it). When I download the file to my computer, I can't open it either and I realize that the downloaded file's size is slighly bigger than the original one (for example of a .docx file: 15.4KB in comparison with 11.3KB).
So I guess the problem is related to the file content before sending it to the server. But I don't know how to fix it yet. Hope you guys could help !