Publish Website Content
Google Drive lets you publish a directory as a website. You can insert static web assets such as HTML, CSS, and image files in a publicly shared folder, and then serve those files directly to users via file names in a relative path. Drive supports JavaScript and other client-side scripting languages, so it's even possible to run a JavaScript Drive app directly from Drive.
The requirements to publish are:
- The folder containing site assets must be public, or "Public on the web." Assets added to public folders must also be public on the web.
- Link to the files contained in the folder using the
webViewLink
folder ID plus the path to the file.
Creating a public folder
To create a public folder programmatically, you'll need to insert a "file" of the MIME type
application/vnd.google-apps.folder
(a type reserved for folders in Drive) and then set the appropriate permissions. The account type must be set to anyone
, and the role
must be reader
.
The following samples demonstrate how to create a public folder using the supported client libraries.
function createPublicFolder(folderName) { var body = { 'title': folderName, 'mimeType': "application/vnd.google-apps.folder" }; var request = gapi.client.drive.files.insert({ 'resource': body }); request.execute(function(resp) { console.log('Folder ID: ' + resp.id); var permissionBody = { 'value': '', 'type': 'anyone', 'role': 'reader' }; var permissionRequest = gapi.client.drive.permissions.insert({ 'fileId': resp.id, 'resource': permissionBody }); permissionRequest.execute(function(resp) { }); }); }
Using the webViewLink
The key to Drive's built-in site publishing is the
webViewLink
provided in the files resource. When you insert a public folder using files.insert, the response contains a webViewLink
entry that looks something like this: "webViewLink": "https://googledrive.com/host/A1B2C3D4E5F6G7H8J9"
Once it has this URL, your app can use it to provide a link to contents in the folder. For example, a link to
kittens.jpg
in an images subfolder could be https://googledrive.com/host/A1B2C3D4E5F6G7H8J9/images/kittens.jpg
You can access the hierarchy of web assets in the folder using file names and relative paths instead of
fileId
values. If you provided a link to anindex.html
file in the folder that contains an image link for kittens.jpg
, then the page displays the image within the page as expected. If you link directly to a folder that lacks a valid index.html
file, Drive displays a simple list of the folder's contents.Extending basic site publishing
The ability to link to files this way opens lots of possibilities for Drive app developers. Writing a blogging tool, creating a process to publish updates to shared docs, outputting images in a folder in a gallery page — any Drive use case that involves presenting a file in a browser can benefit from site publishing. For a larger-scale project, consider the potential to create a site-building IDE for Drive users.