#javascript #google-drive-api
#javascript #google-drive-api
Вопрос:
Я пытаюсь загрузить файл на Google Диск с помощью Google Drive API v3 на JavaScript. Это работает, но как только мой файл загружается на Google Диск, его имя становится «Без названия».
Я заходил на многие темы и форумы Stack Overflow, но не нахожу ответа, потому что многие люди используют Google Drive API v3 с Node.JS, PHP или Python, но не с помощью JavaScript.
Я думаю, мне нужно добавить данные в formData
var, но я не знаю названия этих данных. Я уже пробовал с title
и name
.
Вот мой код :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload to Drive</title>
</head>
<body>
<button id="sign-in-or-out-button" style="margin-left: 25px">Sign In/Authorize</button>
<button id="revoke-access-button" style="display: none; margin-left: 25px">Revoke access</button>
<div id="auth-status" style="display: inline; padding-left: 25px"></div>
<hr>
<div>
<input id="files" type="file" name="files[]" multiple />
<button id="upload">Upload</button>
</div>
</body>
</html>
<script src="./jquery-3.5.1.min.js"></script>
<script>
var GoogleAuth;
var SCOPE = 'https://www.googleapis.com/auth/drive';
let access_token = null;
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': 'AIzaSyBYf75HczHEqCJpQ97tGPOCxybwZFw0gpA',
'clientId': '514528342395-in4priacg29o4vqfqdc9bcjnj0d1c1oj.apps.googleusercontent.com',
'discoveryDocs': [discoveryUrl],
'scope': SCOPE
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function () {
handleAuthClick();
});
$('#revoke-access-button').click(function () {
revokeAccess();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked "Sign out" button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus() {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(SCOPE);
if (isAuthorized) {
access_token = user.xc.access_token;
$('#sign-in-or-out-button').html('Sign out');
$('#revoke-access-button').css('display', 'inline-block');
$('#seeGapi').css('display', 'inline-block');
$('#auth-status').html('You are currently signed in and have granted '
'access to this app.');
} else {
$('#sign-in-or-out-button').html('Sign In/Authorize');
$('#revoke-access-button').css('display', 'none');
$('#auth-status').html('You have not authorized this app or you are '
'signed out.');
}
}
function updateSigninStatus() {
setSigninStatus();
}
// UPLOAD TO DRIVE SECTION
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const redirect_uri = "http://localhost:5500" // replace with your redirect_uri;
const client_secret = "aHgsCY5LUfssabvl5w6Qqtw9"; // replace with your client secret
const scope = "https://www.googleapis.com/auth/drive";
// var access_token = "";
var client_id = "514528342395-in4priacg29o4vqfqdc9bcjnj0d1c1oj.apps.googleusercontent.com" // replace it with your client id;
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function () {
localStorage.setItem("type", this.file.type);
return this.file.type;
};
Upload.prototype.getSize = function () {
localStorage.setItem("size", this.file.size);
return this.file.size;
};
Upload.prototype.getName = function () {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
beforeSend: function (request) {
// request.setRequestHeader("Authorization", "Bearer" " " localStorage.getItem("accessToken"));
request.setRequestHeader("Authorization", "Bearer" " " access_token);
},
url: "https://www.googleapis.com/upload/drive/v2/files",
data: {
uploadType: "media"
},
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id " .progress-bar").css("width", percent "%");
$(progress_bar_id " .status").text(percent "%");
};
$("#upload").on("click", function (e) {
var file = $("#files")[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
Я знаю, что это не идеальный код, но мне нужно успешно задать имя файлу, прежде чем украшать код.
Я надеюсь, что кто-нибудь может помочь.
Хорошего дня 🙂
Комментарии:
1. Рассматривали ли вы возможность ознакомиться с документацией? developers.google.com/drive/api/v3/manage-uploads#node.js он не имеет названия, потому что вы не отправляете метаданные в теле сообщения.
2. В теле метаданные должны стоять на первом месте и должны иметь
Content-Type
заголовок , равныйapplication/json; charset=UTF-8
. Добавьте метаданные файла в формате JSON. Носитель должен быть вторым и должен иметьContent-Type
заголовок любого типа MIME. Добавьте данные файла в мультимедийную часть. — это из документов, на которые ссылается DalmTo в разделе HTTP, поскольку кажется, что вы делаете HTTP-запрос с помощью jquery. Это правильно?3. Привет, DalmTo, да, я уже ознакомился с документацией, но я не нахожу ни одного примера для JavaScript.
4. Привет, янседано, да, я выполняю ajax-запрос с помощью jquery. У вас есть пример запроса, который я должен выполнить, чтобы заставить его работать?
5. Имеете ли вы представление о том, что мне нужно вставить в заголовок (перед запросом), чтобы задать имя для файла? я изменил это в своем коде
beforeSend: function (request) { request.setRequestHeader("Authorization", "Bearer" " " access_token, "title", "myFileName"); },
, но это не сработало.