Wednesday, January 07, 2009

Google Gears Desktop API - Working with files

The Google Gears Desktop API allows you to create shortcuts on your desktop (only to a page on the same site, not to another) and work with files. This example shows you how you can filter the file types when choosing files. gears_init.js required.

<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 <title>Google Desktop API - Working with files</title>
<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript">
var fileformats = {

 // word document
 word: 'application/msword',
 // word 2007 document
 wpml: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',

 // excel spreadsheet
 excel: 'application/vnd.ms-excel',
 // excel 2007 spreadsheet
 ssml: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

 // powerpoint presentation
 powerpoint: 'application/vnd.ms-powerpoint',
 // powerpoint 2007 presentation
 pml: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
 
 // jpeg
 jpeg: 'image/jpeg',
 
 // png
 png: 'image/png',
 
 // gif
 gif: 'image/gif',
 
 // tiff
 tiff: 'image/tiff'
}


// http://code.google.com/apis/gears/api_desktop.html
var desktop = google.gears.factory.create('beta.desktop');

function officeFiles()
{
 desktop.openFiles(openFilesCallback, {singleFile: false,
  filter: [fileformats.word, fileformats.wpml,
   fileformats.excel, fileformats.ssml,
   fileformats.powerpoint, fileformats.pml]
 });
}

function imageFiles()
{
 desktop.openFiles(openFilesCallback, {singleFile: false,
  filter: [fileformats.jpeg, fileformats.png,
   fileformats.gif, fileformats.tiff]
 });
}


function openFilesCallback(files)
{
 if(files.length == 0)
 {
  alert("No files selected");
 }
 else
 {
  var selectedFiles = [];
  for(var i = 0; i < files.length; i++)
  {
   selectedFiles.push(files[i].name + " (" + files[i].blob.length + " bytes)");
  }
  alert("Selected files: " + selectedFiles);
 }
}
</script>
 </head>
 <body>
  <p><a href="http://code.google.com/apis/gears/api_desktop.html">Google Gears Desktop API</a></p>
  <form action="" method="post">
   <input value="Select Office Files" type="button" id="selectofficefiles">
   <input value="Select Image Files" type="button" id="selectimagefiles">
  </form>
<script type="text/javascript">
var selectofficefiles = document.getElementById("selectofficefiles");
selectofficefiles.onclick = function()
{
 officeFiles();
 return false;
}

var selectimagefiles = document.getElementById("selectimagefiles");
selectimagefiles.onclick = function()
{
 imageFiles();
 return false;
}
</script>
 </body>
</html>

The benefit of using Google Gears is that you can get the file size before uploading the file, so a check can be done beforehand to see if the file is to big (e.g. if(files[i].blob.length > 1048576) alert(files[i].name + " too big (> 1MB)");.

No comments: