首先,如果我接下来说的话没有任何意义,请允许我道歉。在这里,我完全超出了我的舒适区,不知道我在做什么。话虽如此...
我正在使用Google Drive文件选择库,允许用户从他们的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.');
}
}
使用上述代码,我接受选择的
file
对象并使用它,连同相关的标头令牌一起下载文件的content
。这似乎按预期工作。然后我的问题出现在尝试将所述内容转换为附加到表单并提交到服务器的
File
时。上面的代码有效,因为文件被服务器接受并相应地上传,但该文件已损坏。我想这是因为我在
file = new File([content], file.title, {type: file.mimeType});
行上做错了什么,但是我已经走得太远,不知道从哪里开始。(我通常不做太多JavaScript,并且只有通过大量复制/粘贴和反复试验才能到达这一步)
可以有人帮助我吗?谢谢。