Issue
I'm struggling to show an image from Google Drive on my HTML page using JavaScript. Following online guides hasn't quite solved it for me.
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google Drive Image</title>
</head>
<body>
<img id="imageElement" alt="A lovely image">
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
const fileId = '1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome';
const imageElement = document.getElementById('imageElement');
async function fetchGoogleDriveImage(fileId) {
try {
const response = await fetch(`https://drive.google.com/uc?id=${fileId}`);
const url = URL.createObjectURL(await response.blob());
imageElement.src = url;
} catch (error) {
console.error('Error fetching the image:', error);
}
}
fetchGoogleDriveImage(fileId);
Context:
- Image in Google Drive is set to "Anyone with the link can view."
- Despite that, the image doesn't load in the browser, and the console shows an error.
Additional HTML (with pure html):
<body>
<img src="https://drive.google.com/uc?id=1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome" alt="Your Image Alt Text">
</body>
Any help is appreciated! Thanks.
Solution
The temporary solution for this would be to replace the Google Drive URLs to a different format that forces the image to be downloaded and displayed. This can be achieved by replacing uc?id=
with thumbnail?id=
and appending &sz=w1000
at the end of the URL. The sz=w1000
parameter specifies the width of the image. You can adjust this value according to your needs.
The final URL format should look like this:
https://drive.google.com/thumbnail?id=FILE_ID&sz=w1000.
eg:
<body>
<img src="https://drive.google.com/thumbnail?id=1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome&sz=w1000" alt="Your Image Alt Text">
</body>
Old URL - "https://drive.google.com/uc?id=1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome"
New URL - "https://drive.google.com/thumbnail?id=1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome&sz=w1000"
You can also use VS Code or any other text editor that has a Regex search to search and replace URL if you have it in bulk: Eg:
Search:
https:\/\/drive\.google\.com\/uc\?id=([^"]+)
Replace:
https://drive.google.com/thumbnail?id=$1&sz=w1000
Using this regex you search and replace all the URLs in your codebase.
Please do note that this is a temporary solution and google might stop the support for thumbnails in the future.
Answered By - Girish
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.