I'm trying to get file from google drive and I'm getting the file contents, converting it to byte array and sending it to backend to save the file on the server(For this I'm using Ajax POST method)
This is what I'm trying to do
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
fileId = data.docs[0].id;
gapi.load('client', function () {
gapi.client.load('drive', 'v3', function () {
var file = gapi.client.drive.files.get({ 'fileId': fileId, fields: '*' });
file.execute(function (resp) {
fileext = resp.originalFilename.split('.').pop();
inputFileName = randomString(8) + "." + fileext;
$('#inputFileName').val(inputFileName);
inputFileName = $('#inputFileName').val();
fileSize = resp.size;
if (fileSize < maxFileSize) {
fileId = resp.id;
accessToken = oauthToken;
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/drive/v3/files/" + fileId + '?alt=media', true);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {//Call a function when the state changes.
if (xhr.readyState == 4 && xhr.status == 200) {
base64 = base64ArrayBuffer(xhr.response);
$.ajax({
type: "POST",
url: "googledrive.aspx/GetDriveFile",
data: JSON.stringify({
FileName: inputFileName, Base64: base64
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d == "true") {
alert("Success");
} else {
alert("Failed");
}
},
error: function (msg) {
alert(msg.d);
}
});
}
}
xhr.send();
} else {
alert("Max File Size");
}
});
});
});
}
}
This is my backend code to save the file to the server
public static string GetDriveFile(string FileName, string Base64)
{
try
{
string inputPath = HttpContext.Current.Server.MapPath("UploadedFiles/") + FileName;
byte[] image64 = Convert.FromBase64String(Base64);
File.WriteAllBytes(inputPath, image64);
return "true";
}
catch (Exception ex)
{
return ex.ToString();
}
}
I'm using the base64 conversion from here
The Ajax POST method is not triggering and getting 500 internal server error as shown.