使用Javascript将文本从Textarea保存到Google Drive
我正在尝试将键入文本区域的文本上载到Google驱动器文件(mimetype:text/x-java for java源代码) 我曾尝试合并中提到的update和insert方法,但不断出现401错误。可在上找到实现 任何帮助都将不胜感激使用Javascript将文本从Textarea保存到Google Drive,javascript,google-drive-api,Javascript,Google Drive Api,我正在尝试将键入文本区域的文本上载到Google驱动器文件(mimetype:text/x-java for java源代码) 我曾尝试合并中提到的update和insert方法,但不断出现401错误。可在上找到实现 任何帮助都将不胜感激 // save content to google drive function updateOrInsert(fileId, folderId, text, callback) { const boundary = '-------31
// save content to google drive
function updateOrInsert(fileId, folderId, text, callback)
{
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
checkAuth();
var contentType = "text/x-java";
var myToken = accesstoken || gapi.auth.getToken();
// if fileId exists, the file exists, use update method
if (fileId)
{
var metadata = {'mimeType': contentType,};
var multipartRequestBody =
delimiter + 'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter + 'Content-Type: ' + contentType + '\r\n' + '\r\n' +
text +
close_delim;
if (!callback) { callback = function(file) { console.log("Update Complete ",file) }; }
gapi.client.request({
'path': '/upload/drive/v2/files/'+folderId+"?fileId="+fileId+"&uploadType=multipart",
'method': 'PUT',
'params': {'fileId': fileId, 'uploadType': 'multipart'},
'headers': { 'Authorization': 'Bearer '+myToken.access_token,
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'},
'body': multipartRequestBody,
});
}
else
{
//no file present, must create a new one. use insert method
var reader = new FileReader();
var fileData = new Blob([text], {type:'text/x-java'});
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
var contentType = fileData.type || 'text/x-java';
var metadata = {
'title': filename,
'mimeType': contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request(
{
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Authorization': 'Bearer '+myToken.access_token,
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody
} );
if (!callback)
{
callback = function(file) { console.log(file) };
}
request.execute(callback);
}
}
}
我查看了试图将文档保存到google的网络选项卡,它似乎返回了一个身份验证错误,您查看了他们的客户端身份验证文档了吗 这里是错误
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
尝试签出并尝试使用javascript
<html>
<head>
<script type="text/javascript">
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = '<YOUR_CLIENT_ID>';
var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadDriveApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Drive API client library.
*/
function loadDriveApi() {
gapi.client.load('drive', 'v3', listFiles);
}
/**
* Print files.
*/
function listFiles() {
var request = gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
});
request.execute(function(resp) {
appendPre('Files:');
var files = resp.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
/**
* Append a pre element to the body containing the given message
* as its text node.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to Drive API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<pre id="output"></pre>
</body>
</html>
//您的客户ID可以从Google中的项目中检索
//开发者控制台,https://console.developers.google.com
var客户端ID=“”;
变量作用域=['https://www.googleapis.com/auth/drive.metadata.readonly'];
/**
*检查当前用户是否已授权此应用程序。
*/
函数checkAuth(){
gapi.auth.authorize(
{
“客户id”:客户id,
“scope”:SCOPES.join(“”),
“立即”:真
},handleAuthResult);
}
/**
*处理来自授权服务器的响应。
*
*@param{Object}authResult授权结果。
*/
函数handleAuthResult(authResult){
var authorizeDiv=document.getElementById('authorized-div');
if(authResult&!authResult.error){
//隐藏身份验证UI,然后加载客户端库。
authorizeDiv.style.display='none';
loadDriveApi();
}否则{
//显示授权UI,允许用户通过
//单击“授权”按钮。
authorizeDiv.style.display='inline';
}
}
/**
*响应用户单击“授权”按钮,启动身份验证流。
*
*@param{Event}Event按钮单击事件。
*/
函数handleAuthClick(事件){
gapi.auth.authorize(
{client_id:client_id,scope:SCOPES,immediate:false},
手工(结果);
返回false;
}
/**
*加载驱动器API客户端库。
*/
函数loadDriveApi(){
load('drive','v3',listFiles);
}
/**
*打印文件。
*/
函数listFiles(){
var request=gapi.client.drive.files.list({
“页面大小”:10,
“字段”:“下一个GetOken,文件(id,名称)”
});
请求执行(功能(resp){
appendPre('Files:');
var files=resp.files;
如果(files&&files.length>0){
对于(var i=0;i
这将是熟悉代码和使用驱动API时所需的一些步骤的有用方法。希望能有所帮助。那么,添加
var myToken=gapi.auth.getToken()
和'Authorization':'Bearer'+myToken.access\u token,
在标题中修复了这一点(就像我对加载方法所做的那样)?正如Rebot先生所暗示的,401个错误(而且,你会发现,还有一些其他错误)意味着你的呼叫没有被授权。如果已在中设置应用程序和凭据,则用户必须访问该应用程序才能访问其驱动器。如果您使用的是gapi,那么它将存储并使用授权,但是对于直接的http调用,您还可以添加access_令牌作为查询参数:?access_令牌=xyzblahblahblah。这很痛苦,但这是一次性设置。我调用了页面中的authorize()
。所以源代码看起来像:。。。const close_delim=“\r\n--”+边界+“--”;checkAuth();var contentType=“text/x-java”;var myToken=gapi.auth.getToken()代码>和更高版本的。。。gapi.client.request({'path':'/upload/drive/v2/files/'+folderId+“?fileId=“+fileId+”&uploadType=multipart“,'method':'PUT','params':{'fileId':fileId,'uploadType':'multipart','headers':{'Authorization':'Bearer'+myToken.access_-token',Content Type':'multipart/mixed;body=“+boundary+”,},'body':multipartRequestBody,})
但仍然不行。我无法读取未定义的属性'access_-token'。我调用checkAuth()
,然后使用var myToken=accesstoken | | | gapi.auth.getToken();
检查是否存在现有的accesstoken(来自全局变量)或者我需要获得一个新的令牌。错误是当我在方法的插入部分添加标题“Authorization':“Bearer”+myToken.access\u token,
。在这两种情况下,新的更改都不会在Google驱动器文件中更新。搁置您的项目,您尝试过javascript快速启动吗?这肯定会帮助您理解它驱动程序API中的身份验证流程。请更新您的帖子,让我们看看您在代码中更新了什么。提前感谢:)我已经更新了上面的代码。快速启动what where,但它没有反映如何写入Google drive。和是我尝试在上面使用快速启动的授权实现的(以及在“我的文件读取”功能中工作的身份验证。)