我从谷歌跟踪了整个步骤,我得到了一些我在这里找到的代码,所以我正在尝试使用API将表单中的文件上传到Google云端硬盘,这就是代码:
doWork()
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
})
谷歌收到信息,并创建文件,问题是该文件似乎不是谷歌或我不知道,所有我得到的只是没有内容的谷歌文件。当我尝试上传样本时,一切顺利。
答案 0 :(得分:2)
我认为你的脚本几乎是正确的。但它需要修改一点。那么这个修改怎么样?我认为你的情况有几个答案。所以请把它想象成其中之一。
'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().
Google receives the information, and creates the file
,您的脚本已准备好用于上传文件。虽然在我的环境中,我确认这个脚本有效,如果这对你的情况没用,我很抱歉。