Are you looking for a way to dynamically list files from a Google Drive folder, complete with file names, sizes, and links, that you can easily share on a website or embed in an HTML page? With Google Apps Script, you can achieve this efficiently. This blog post introduces a script function, listFilesInFolder(folderId)
, that generates a structured HTML list of files from a specific Google Drive folder.
What Does the Script Do?
The listFilesInFolder
function allows you to:
- List all the files within a specified folder in Google Drive.
- Display file names, sizes (in MB), and whether they are PDFs.
- Generate clickable links to the files, making it ideal for embedding on websites or sharing file resources.
How It Works
Here’s how the function is structured:
- Access the Folder:
The script usesDriveApp.getFolderById(folderId)
to access the folder specified by its unique ID. - Retrieve Files:
It iterates over the files in the folder usingfolder.getFiles()
. - Generate HTML Output:
For each file, the script:- Fetches the file name, size (converted to MB), and URL.
- Checks if the file is a PDF using the MIME type.
- Appends this data as a list item in an HTML unordered list.
- Handle Errors Gracefully:
If an error occurs, it logs the error and returns the error message.
The Full Code
Here is the complete function:
function listFilesInFolder(folderId) {
try {
// Open the folder using the folderId
const folder = DriveApp.getFolderById(folderId);
const files = folder.getFiles();
// HTML structure
let htmlOutput = '<ul>';
while (files.hasNext()) {
const file = files.next();
const fileName = file.getName();
const fileSize = (file.getSize() / (1024 * 1024)).toFixed(2) + ' MB'; // Convert size to MB
const fileUrl = file.getUrl();
// Check if the file is a PDF
const isPdf = file.getMimeType() === 'application/pdf';
// Append to HTML
htmlOutput += `<li>
<a href="${fileUrl}" target="_blank">${fileName}</a>
(Size: ${fileSize}, Type: ${isPdf ? 'PDF' : 'Other'})
</li>`;
}
htmlOutput += '</ul>';
return htmlOutput;
} catch (e) {
console.error(e.toString());
return `Error: ${e.toString()}`;
}
}
Steps to Run the Script
- Set Up the Script:
- Open Google Apps Script.
- Create a new project, paste the updated code, and save it.
- Replace the Folder ID:
- Replace
folderId
in the function call withyour ID
(the ID of your provided folder).
- Replace
- Run the Script:
- Call the
listFilesInFolder()
function from the script editor. - The function will return HTML containing links, file names, sizes, and whether they are PDFs.
- Call the
- Deploy as Web App (Optional):
- If you want to use this script on a website, go to
Deploy > New deployment
, choose “Web app,” and set access permissions.
- If you want to use this script on a website, go to
- Page Count for PDFs:
- Extracting the number of pages from a PDF is not directly supported by Google Apps Script. For advanced requirements like this, you can:
- Use an external library (e.g., PDF.js) for client-side processing.
- Use a third-party service/API like Adobe PDF Tools API to extract metadata.
- Extracting the number of pages from a PDF is not directly supported by Google Apps Script. For advanced requirements like this, you can:
How to Use the Script
- Access Google Apps Script:
- Go to Google Apps Script.
- Create a new script project.
- Add the Code:
Copy and paste thelistFilesInFolder
function into the Apps Script editor. - Provide the Folder ID:
ReplacefolderId
with the unique ID of your Google Drive folder. You can find this ID in the folder’s URL:rubyCopy codehttps://drive.google.com/drive/folders/<FOLDER_ID>
- Run the Script:
Execute the function and capture the HTML output. - Embed in HTML:
Use the generated HTML output in your web page to display the file list.
Example Output
For a folder containing several files, the function generates the following HTML:
<ul>
<li><a href="https://drive.google.com/file/d/example1" target="_blank">Document1.pdf</a> (Size: 2.10 MB, Type: PDF)</li>
<li><a href="https://drive.google.com/file/d/example2" target="_blank">Image1.png</a> (Size: 1.35 MB, Type: Other)</li>
<li><a href="https://drive.google.com/file/d/example3" target="_blank">Presentation.pptx</a> (Size: 5.80 MB, Type: Other)</li>
</ul>
When embedded on a website, it renders as:
- Document1.pdf (Size: 2.10 MB, Type: PDF)
- Image1.png (Size: 1.35 MB, Type: Other)
- Presentation.pptx (Size: 5.80 MB, Type: Other)
Why This Script Is Useful
- Automation: Eliminate manual file listing and updating.
- Dynamic Content: Embed real-time file updates on your website.
- Improved Sharing: Easily distribute links to files with additional metadata.
Next Steps
Ready to take it a step further? Here are a few ideas to enhance the script:
- Filter Files: Display only specific file types, such as PDFs or images.
- Sort Files: Sort the list alphabetically or by file size.
- Custom Styling: Add CSS to style the generated HTML.
This simple yet powerful script makes it easy to manage and share Google Drive files dynamically. Whether you’re a teacher, developer, or administrator, this tool can save you time and effort.