App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
import React, { useEffect, useState } from "react"; import { Container, Button, ListGroup, Row, Col, Form } from "react-bootstrap"; import { GoogleLogin } from "react-google-login"; import { gapi } from "gapi-script"; import "bootstrap/dist/css/bootstrap.min.css"; // Your Google Client ID const CLIENT_ID = ""; const App = () => { const [isAuthenticated, setIsAuthenticated] = useState(false); const [files, setFiles] = useState([]); const [error, setError] = useState(""); const [selectedFile, setSelectedFile] = useState(null); // Load Google API client useEffect(() => { gapi.load("client:auth2", initClient); }, []); // Initialize the Google API client const initClient = () => { gapi.client.init({ apiKey: "AIzaSyD_GVnWwh42673ikySb0WRAjpteVg2GPT4", // Your API key clientId: CLIENT_ID, scope: "https://www.googleapis.com/auth/drive.file", discoveryDocs: [ "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest", ], }); }; // Handle login success const handleLoginSuccess = (response) => { setIsAuthenticated(true); gapi.auth2.getAuthInstance().signIn(); listFiles(); }; // Handle login failure const handleLoginFailure = (response) => { setError("Failed to authenticate with Google."); }; // List files from Google Drive const listFiles = () => { gapi.client.drive.files .list({ pageSize: 10, fields: "files(id, name, mimeType)" }) .then((response) => { setFiles(response.result.files); }) .catch((err) => { setError("Error fetching files from Google Drive."); console.error(err); }); }; // Download file function // Download file function const downloadFile = (fileId, fileName) => { const accessToken = gapi.auth.getToken().access_token; // Get the access token fetch(https://www.googleapis.com/drive/v3/files/${fileId}?alt=media, { headers: { Authorization: Bearer ${accessToken}, }, }) .then((response) => { if (!response.ok) { throw new Error("Failed to download the file."); } return response.blob(); // Convert the response to a Blob }) .then((blob) => { const url = window.URL.createObjectURL(blob); // Create a download URL const link = document.createElement("a"); link.href = url; link.download = fileName; // Set the file name document.body.appendChild(link); link.click(); // Trigger the download document.body.removeChild(link); // Clean up }) .catch((err) => { setError("Error downloading the file."); console.error(err); }); }; // Upload file function const uploadFile = () => { if (!selectedFile) { setError("Please select a file to upload."); return; } const fileMetadata = { name: selectedFile.name, }; const formData = new FormData(); formData.append( "metadata", new Blob([JSON.stringify(fileMetadata)], { type: "application/json" }) ); formData.append("file", selectedFile); fetch( "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", { method: "POST", headers: { Authorization: Bearer ${gapi.auth.getToken().access_token}, }, body: formData, } ) .then((response) => response.json()) .then(() => { setError(""); setSelectedFile(null); listFiles(); // Refresh the file list }) .catch((err) => { setError("Error uploading the file."); console.error(err); }); }; return ( <Container className="my-4"> <h1 className="text-center">Google Drive File Viewer</h1> {!isAuthenticated ? ( <GoogleLogin clientId={CLIENT_ID} buttonText="Login with Google" onSuccess={handleLoginSuccess} onFailure={handleLoginFailure} cookiePolicy="single_host_origin" scope="https://www.googleapis.com/auth/drive.file" /> ) : ( <> <h5>Files in Google Drive</h5> {error && <div className="alert alert-danger">{error}</div>} <div className="d-flex justify-content-between mb-3"> <Form.Control type="file" onChange={(e) => setSelectedFile(e.target.files[0])} style={{ maxWidth: "300px" }} /> <Button variant="success" onClick={uploadFile}> Upload File </Button> <Button variant="primary" onClick={listFiles}> Refresh List </Button> </div> <ListGroup> {files.map((file) => ( <ListGroup.Item key={file.id}> <Row className="align-items-center"> <Col> <a href={https://drive.google.com/file/d/${file.id}/view} target="_blank" rel="noopener noreferrer" > {file.name} </a> </Col> <Col xs="auto"> <Button variant="primary" onClick={() => downloadFile(file.id, file.name)} > Download </Button> </Col> </Row> </ListGroup.Item> ))} </ListGroup> </> )} </Container> ); }; |