First off, please allow me to apologise if none of what I'm about to say makes any sense. I'm well out of my comfort zone here and don't really know what I'm doing. With that said...
I'm using the Google Drive File Picker library to allow users to upload their CV from their Google Drive.
function downloadGDriveFile(file) { if (file.downloadUrl) { var accessToken = gapi.auth.getToken().access_token; var xhr = new XMLHttpRequest(); xhr.open('GET', file.downloadUrl); xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); xhr.onload = function () { var content = xhr.response; console.log(xhr); form_element = document.getElementById("new_guest_application"); form_data = new FormData(form_element); new_file = new File([content], file.title, {type: file.mimeType}); form_data.append('guest_application[curriculum_vitae]', new_file); console.log(new_file); var request = new XMLHttpRequest(); request.open("POST", form_element.action); request.send(form_data); }; xhr.onerror = function () { alert('Download failure.'); }; xhr.send(); } else { alert('Unable to download file.'); } }
Using the code above, I'm accepting the selected file
object and using it, along with the relevant header token, to download the content
of the file. This appears to be working as intended.
My issue then comes when trying to turn said content into a File
for attaching to a form and submitting to my server.
The code above works, in so far as a file is accepted by the server and uploaded accordingly, but said file is corrupted. I'd imagine this is because I'm doing something wrong with the file = new File([content], file.title, {type: file.mimeType});
line, but I'm so far outside my comfort zone, that I don't even know where to begin.
(I don't do much JavaScript as a rule, and have only managed to get this far with a healthy dose of copy/paste trial and error)
Can someone help me out? thanks.
1 Answers
Answers 1
xhr.response
will return some data formatted depending on the data type defined in xhr.responseType
. If you a carrying binary data, and responseType
is set to a text type, your data will be corrupted.
You can try to override xhr.responseType
just before reading the response
xhr.responseType = "arraybuffer"; var content = xhr.response;
0 comments:
Post a Comment