I would like to host around 300 photo on Google drive and be able to fetch every photo on my react project, but I don't know how to start like should I need a back-end like node.js? I've seen this video (), but he displays only 1 photo.
I wanna display all my images from Google drive on the React and put it on a array like this following JSON
const photos = [
{
src: '',
width: 4,
height: 3,
year: '2021',
event: 'Hiking',
},
{
src: '',
width: 1,
height: 1,
year: '2021',
event: 'J-On',
},
{
src: '',
width: 3,
height: 4,
year: '2021',
event: 'Language Exchange',
},
and so on...
I would like to host around 300 photo on Google drive and be able to fetch every photo on my react project, but I don't know how to start like should I need a back-end like node.js? I've seen this video (https://www.youtube./watch?v=iajv8y-6n3Q), but he displays only 1 photo.
I wanna display all my images from Google drive on the React and put it on a array like this following JSON
const photos = [
{
src: 'https://source.unsplash./2ShvY8Lf6l0/800x599',
width: 4,
height: 3,
year: '2021',
event: 'Hiking',
},
{
src: 'https://source.unsplash./Dm-qxdynoEc/800x799',
width: 1,
height: 1,
year: '2021',
event: 'J-On',
},
{
src: 'https://source.unsplash./qDkso9nvCg0/600x799',
width: 3,
height: 4,
year: '2021',
event: 'Language Exchange',
},
and so on...
Share
Improve this question
asked Jul 5, 2022 at 6:06
Kimora X LoveKimora X Love
311 silver badge2 bronze badges
2
- developers.google./drive/api/quickstart/js – Andy Commented Jul 5, 2022 at 6:16
-
Hi, thanks for your question. It made me curious. I've just updated my answer by adding
NextJS
andgoogleapis
data fetching so you can fetch it automatically from google drive. I tested the app before posting the update. So, I am sure it will work if you follow the instruction. – yohanes Commented Jul 7, 2022 at 8:25
1 Answer
Reset to default 5You can achieve your goal in two ways:
- Get the files link by manually copying the link from google drive
- Fetch the data by using
Next.js
app andgoogleapis
.
1. Get the files link by manually copying the link from google drive:
- Open the file on google drive
- Right click at the image file
- Click
Get Link
and a pop up will open - At
General Access
selectAnyone with the link
and make sure the role isViewer
- Click
Copy Link
and done.
Then paste it at any text editor, and you will get the link like this:
https://drive.google./file/d/1WS45ByTh_e8QNJTeFMGI8TYpE4OYS2U4/view?usp=sharing
Remove the file/d
and replace it with uc?export=view&id=
and remove the /view?usp=sharing
pletely and you will get something like:
https://drive.google./uc?export=view&id=1WS45ByTh_e8QNJTeFMGI8TYpE4OYS2U4
And put the image information in an array:
const images = [
{
name: "Doctor Strange in the Multiverse of Madness",
src: "https://drive.google./uc?export=view&id=1WS45ByTh_e8QNJTeFMGI8TYpE4OYS2U4"
}
]
Please do the same with the other files, and your images constant finally looks like this:
const images = [
{
name: "Doctor Strange in the Multiverse of Madness",
src:
"https://drive.google./uc?export=view&id=1WS45ByTh_e8QNJTeFMGI8TYpE4OYS2U4",
},
{
name: "Minions: The Rise of Gru",
src:
"https://drive.google./uc?export=view&id=1eUvlVjwp2brHnyD-cWN0x-10tuS_wXfU",
},
...
,
{
name: "Fantastic Beasts: The Secrets of Dumbledore",
src:
"https://drive.google./uc?export=view&id=1vU64yCMdu_ns4xPP-VMYoiJPKNietxRc",
},
];
Now, it is time to render the images in our React Application by using javascript's map method:
export default function App() {
return (
<div>
<div>My Google Drive Images</div>
<ul>
{images.map((image, index) => {
return (
<li key={index}>
<h1>{image.name}</h1>
<img src={image.src} alt={image.name} />
</li>
);
})}
</ul>
</div>
);
}
2. Fetch the data by using Next.js
app and googleapis
.
In case we have many photos, it is better to use data fetching. Here we use Next.js app and googleapis library.
There are 3 pieces of information that we need to provide in order to be able to fetch data from https://www.googleapis./drive/v2
server which are:
- CLIENT_ID
- CLIENT_SECRET
- REFRESH_TOKEN
For CLIENT_ID
& CLIENT_SECRET
are OAuth 2.0 Client information that can be obtained from Google Developers Console. You can read the details here. And for the REFRESH_TOKEN
can be obtained from OAuth 2.0 Playground and the steps are as follows:
- Go to https://developers.google./oauthplayground
- Click the
OAuth 2.0 Configuration
button - Click
Use your own OAuth credentials
checkbox - Fill the Client ID & Client Secret input with the OAuth 2.0 CLIENT_ID & CLIENT_SECRET that we get from Google Developers Console.
- Close the configuration popup by clicking the close link button.
- Find and click the Drive API v3 at Step 1 Select & authorizes APIs.
- Select
https://www.googleapis./auth/drive
to enable the Authorize APIs button. - Next we need to select which information that can be accessed by using the token that will be created by clicking the
Authorize APIs
button. - Then we will be directed to the
Sign in with google
page. Select the account that we used to generate the CLIENT_ID & CLIENT_SECRET. - If the
Google hasn’t verified this app
page appears, just click Advance and click Go to ...(unsafe) and select the access types that will be granted to our Next.js app then clickContinue
and you will be redirected to OAuth 2.0 Playground again. - Find the
Exchange authorization code for tokens
button atStep 2 Exchange authorization code for tokens
, and click it to get theRefresh token
andAccess token
- To make sure that we have generated the tokens correctly, go to
https://www.googleapis./drive/v2/files?access_token={ACCESS_TOKEN}
in your browser. Our configuration is successful if there is a raw JSON page that shows our drive items.
Now, we are ready for coding. We will use our NextJs API to municate with googleapis
server and serve the data to be consumed by our app.
Open your Nextjs app, create a /pages/api/drive-files.ts
file, and import googleapis
library (here we use Typescript).
import type { NextApiRequest, NextApiResponse } from "next";
import { google } from "googleapis";
...
Create types:
type DriveFile = {
kind: string;
id: string;
name: string;
mimeType: "image/jpeg";
};
type Data = {
files: DriveFile[];
};
Add the Data type at the NextApiResponse and the handler will look like this:
export default async function handler(
_req: NextApiRequest,
res: NextApiResponse<Data>
) {
...
}
Next, create oauth2Client
that use CLIENT_ID and CLIENT_SECRET credentials and we use https://developers.google./oauthplayground
as the redirect uri, setCredentials
using REFRESH_TOKEN, and return the google.drive
response as JSON;
# /pages/api/drive-files.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { google } from "googleapis";
export type DriveFile = {
kind: string;
id: string;
name: string;
mimeType: "image/jpeg";
};
export type Data = {
files: DriveFile[];
};
const CLIENT_ID =
"777777777777-xxxxddhsl77d7o77777xxxx0v777xx7.apps.googleusercontent.";
const CLIENT_SECRET = "XXXXXX-777XXXX_-7-hexxxxheAzW_7mr_7_";
const REDIRECT_URI = "https://developers.google./oauthplayground";
export default async function handler(
_req: NextApiRequest,
res: NextApiResponse<Data>
) {
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oauth2Client.setCredentials({
refresh_token:
"1//04tORk-dUiDiJCgYIARAAGAQSNwF-L9Ir1hzh14oOk6gQWMOafDZGvLuka578PwwmZB3UMbB2a0VdcjAbRjtelFoDU92ob_Ws50I",
});
const drive = google.drive({
version: "v3",
auth: oauth2Client,
params: {
q: `mimeType = 'image/jpeg'`,
},
});
const response = await drive.files.list();
res.status(200).json({ files: response.data.files as DriveFile[] });
}
And when you access http://localhost:3000/api/drive-files
from the browser, you will get:
{
"files":[
{
kind: 'drive#file',
id: '1eUvlVjwp2brHnyD-cWN0x-10tuS_wXfU',
name: 'Minions: The Rise of Gru.jpg',
mimeType: 'image/jpeg'
},
{
kind: 'drive#file',
id: '1vU64yCMdu_ns4xPP-VMYoiJPKNietxRc',
name: 'Fantastic Beasts: The Secr.jpg',
mimeType: 'image/jpeg'
},
{
kind: 'drive#file',
id: '1WS45ByTh_e8QNJTeFMGI8TYpE4OYS2U4',
name: 'Doctor Strange in the M.jpg',
mimeType: 'image/jpeg'
}
]
}
Since we will use NextJs Image
ponent, don't forget to add domain drive.google.
at next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ["drive.google."],
},
};
module.exports = nextConfig;
Finally, you can render the images as follows:
import { useEffect, useState } from "react";
import type { NextPage } from "next";
import axios from "axios";
import { DriveFile } from "./api/drive-files";
import Image from "next/image";
const DriveFiles: NextPage = () => {
const [files, setFiles] = useState<DriveFile[]>();
useEffect(() => {
axios
.get("/api/drive-files")
.then((res) => {
setFiles(res.data.files);
})
.catch((err) => {
console.log(err);
});
}, []);
useEffect(() => {
console.log(files);
}, [files]);
return (
<>
<h1>Google Drive Files</h1>
{files &&
files.map((file, i) => {
return (
<div key={i}>
<p>{file.name}</p>
<Image
width={200}
height={300}
src={`https://drive.google./uc?export=view&id=${file.id}`}
alt={file.name}
/>
</div>
);
})}
</>
);
};
export default DriveFiles;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745202539a4616413.html
评论列表(0条)