Bug 1034828 - Browser API download method should add extension to file if not present. r=kanru, a=2.0+
authorGhislain 'Aus' Lacroix <glacroix@mozilla.com>
Tue, 15 Jul 2014 03:05:44 -0700
changeset 208037 8502e15d3a77a32883c0c82bdac7eaac89669540
parent 208036 21823bcb1ce9eb600b18918e90bc300d98ed3e0f
child 208038 73891d7ac22ca27d76ca9b4a4f45330c0b1941ba
push id3741
push userasasaki@mozilla.com
push dateMon, 21 Jul 2014 20:25:18 +0000
treeherdermozilla-beta@4d6f46f5af68 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerskanru, 2
bugs1034828
milestone32.0a2
Bug 1034828 - Browser API download method should add extension to file if not present. r=kanru, a=2.0+
dom/browser-element/BrowserElementParent.jsm
--- a/dom/browser-element/BrowserElementParent.jsm
+++ b/dom/browser-element/BrowserElementParent.jsm
@@ -621,16 +621,36 @@ BrowserElementParent.prototype = {
       extListener: null,
       onStartRequest: function(aRequest, aContext) {
         debug('DownloadListener - onStartRequest');
         let extHelperAppSvc =
           Cc['@mozilla.org/uriloader/external-helper-app-service;1'].
           getService(Ci.nsIExternalHelperAppService);
         let channel = aRequest.QueryInterface(Ci.nsIChannel);
 
+        // First, we'll ensure the filename doesn't have any leading
+        // periods. We have to do it here to avoid ending up with a filename
+        // that's only an extension with no extension (e.g. Sending in
+        // '.jpeg' without stripping the '.' would result in a filename of
+        // 'jpeg' where we want 'jpeg.jpeg'.
+        _options.filename = _options.filename.replace(/^\.+/, "");
+
+        let ext = null;
+        let mimeSvc = extHelperAppSvc.QueryInterface(Ci.nsIMIMEService);
+        try {
+          ext = '.' + mimeSvc.getPrimaryExtension(channel.contentType, '');
+        } catch (e) { ext = null; }
+
+        // Check if we need to add an extension to the filename.
+        if (ext && !_options.filename.endsWith(ext)) {
+          _options.filename += ext;
+        }
+        // Set the filename to use when saving to disk.
+        channel.contentDispositionFilename = _options.filename;
+
         this.extListener =
           extHelperAppSvc.doContent(
               channel.contentType,
               aRequest,
               interfaceRequestor,
               true);
         this.extListener.onStartRequest(aRequest, aContext);
       },