我遵循了google的所有步骤,我在这里找到了一些代码,所以我尝试使用API将表单中的文件上传到Google Drive,这就是代码:
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
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
谷歌接收到信息,并创建文件,问题是,似乎该文件不会去谷歌或我不知道,我所得到的只是谷歌文件没有内容。当我试着做一个样本上传时,一切都很顺利。
发布于 2018-05-16 00:08:28
我认为你的剧本几乎是正确的。但它需要稍微修改一下。那么这次修改怎么样?我认为你的处境有几个答案。所以请把这当成他们中的一员。
修改要点:
'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,您的脚本已经准备好用于上传文件。
虽然在我的环境中,我确认了这个脚本是有效的,如果这对您的情况没有用,我很抱歉。
https://stackoverflow.com/questions/50357074
复制相似问题