Extracted from https://github.com/romelgomez/angular-firebase-image-upload/blob/master/app/scripts/fileUpload.js#L89
3390
function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
    var deferred = $q.defer();
    var canvasElement = document.createElement('canvas');
    var imageElement = document.createElement('img');
    imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
    document.body.appendChild(imageElement);

    imageElement.onload = function () {
      var imgWidth = imageElement.width, imgHeight = imageElement.height;
      imageElement.parentNode.removeChild(imageElement);
      if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
        deferred.reject('resizeIf');
        return;
      }
      try {
        if (ratio) {
          var ratioFloat = upload.ratioToFloat(ratio);
          var imgRatio = imgWidth / imgHeight;
          if (imgRatio < ratioFloat) {
            width = imgWidth;
            height = width / ratioFloat;
          } else {
            height = imgHeight;
            width = height * ratioFloat;
          }
        }
        if (!width) {
          width = imgWidth;
        }
        if (!height) {
          height = imgHeight;
        }
        var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
        canvasElement.width = Math.min(dimensions.width, width);
        canvasElement.height = Math.min(dimensions.height, height);
        var context = canvasElement.getContext('2d');
        context.drawImage(imageElement,
          Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
          dimensions.width, dimensions.height);
        deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
      } catch (e) {
        deferred.reject(e);
      }
    };
    imageElement.onerror = function () {
      imageElement.parentNode.removeChild(imageElement);
      deferred.reject();
    };
    imageElement.src = imagen;
    return deferred.promise;
  }
1208532
function pipePhotoPostHandler(){

    var fileNameValue =  $('#filename').val() || _photoToUse.split('/').pop() || 'photopipe_'
    var fileExtension = ''
    var hasFileExt = (/\.(gif|jpg|jpeg|png|bmp)/gi.exec(_photoToUse))
    var fileExtension = (hasFileExt && hasFileExt.length) ? hasFileExt[0] : '.jpg'

    fileNameValue = encodeURI( (fileNameValue + fileExtension) )

    // If the filebegins with a question mark, make it empty string
    if(fileNameValue.charAt(0) === '?') fileNameValue = ''
    
    console.dir(hasFileExt)
    console.log(fileExtension)    
    console.log(fileNameValue)    
    console.log(_photoToUse)
    
    $
    .post("/smoke",{
      type: _photoDestination,
      photoUrl: localStorage.imageToPipe,
      filename: fileNameValue,
      caption: $caption.val() || null
    })
    .success(function(data){ 

      $spin.hide()

      if(_photoDestination === 'download'){
        // console.dir(data)
        downloadFile(data)
      }
      else{
        // console.dir(data)
        alert('Success!')
        // window.location = "/"
      }

    })
    .error(function(e) {
      $spin.hide()
      if(e.status === 400) alert(e.responseText || 'Bad request.')
      if(e.status === 401) alert(e.responseText || 'Unauthorized request.')
      if(e.status === 402) alert(e.responseText || 'Forbidden request.')
      if(e.status === 403) alert(e.responseText || 'Forbidden request.')
      if(e.status === 404) alert(e.responseText || 'Images were not found.')
      if(e.status === 405) alert(e.responseText || 'That method is not allowed.')
      if(e.status === 408) alert(e.responseText || 'The request timed out. Try again.')
      if(e.status === 500) alert(e.responseText || 'Something went really wrong.')
      
      // TODO: RESTART AT STEP ONE? 0N 403 YES.
      if(e.status === 403 && (e.responseText.regexIndexOf(/twitter/gi) > -1)) window.location = "/twitter"
      if(e.status === 403 && (e.responseText.regexIndexOf(/facebook/gi) > -1)) window.location = "/facebook"
      if(e.status === 403 && (e.responseText.regexIndexOf(/instagram/gi) > -1)) window.location = "/instagram"
    })
    
    return false
    
  }
404279
function () {
    this.canvas.toBlob(function (blob) {
      var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
      var linkEl = document.createElement('a');
      var url = URL.createObjectURL(blob);
      linkEl.href = url;
      linkEl.setAttribute('download', fileName);
      linkEl.innerHTML = 'downloading...';
      linkEl.style.display = 'none';
      document.body.appendChild(linkEl);
      setTimeout(function () {
        linkEl.click();
        document.body.removeChild(linkEl);
      }, 1);
    }, 'image/png');
  }
324772
function createUploadPromise(filepath, destination, options) {
    return function () {
      // get the name of the file and construct the url for uploading it
      var filename = getFilename(filepath),
        dropboxPath = destination + (options.version_name ? ("/" + options.version_name + "/") : "/") + filepath,
        // read the file and start the upload, decrementing the in-flight count when complete
        // Use encoding = null to keep the file as a Buffer
        reqOptions = {
          access_token: options.access_token,
          dropboxPath: dropboxPath,
          fileBuffer: grunt.file.read(filepath, { encoding : null })
        };

      grunt.log.writeln("Uploading " + filepath + " to " + dropboxPath + "...");

      // return the upload promise
      return dropboxClient.upload(reqOptions);
    };
  }
954286
public function actionUpload()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new Mediafile();
        $routes = $this->module->routes;
        $rename = $this->module->rename;
	    $tagIds = Yii::$app->request->post('tagIds');

	    if ($tagIds !== 'undefined') {
		    $model->setTagIds(explode(',', $tagIds));
	    }

        $model->saveUploadedFile($routes, $rename);
        $bundle = FilemanagerAsset::register($this->view);

        if ($model->isImage()) {
            $model->createThumbs($routes, $this->module->thumbs);
        }

        $response['files'][] = [
            'url'           => $model->url,
            'thumbnailUrl'  => $model->getDefaultThumbUrl($bundle->baseUrl),
            'name'          => $model->filename,
            'type'          => $model->type,
            'size'          => $model->file->size,
            'deleteUrl'     => Url::to(['file/delete', 'id' => $model->id]),
            'deleteType'    => 'POST',
        ];

        return $response;
    }
944070
function initModule($fh, cameraOptionsBuilder, mode) {
  var moduleName = 'wfm.step.gallery';
  // require http module to get server baseUrl
  var ngModule = angular.module(moduleName, []);

  require('../../dist');

  ngModule.directive('gallery', function($templateCache) {
    return {
      restrict: 'E'
      , template: $templateCache.get('wfm-template/gallery.tpl.html')
      , controller: function($scope) {
        var self = this;

        getServerUrl($fh).then(function(serverBaseUrl) {
          var baseFileUrl = new URL('/file/', serverBaseUrl);
          $scope.pictures = self.getPictures(baseFileUrl);
        });

        self.getPictures = function(baseFileUrl) {
          var gallery = $scope.result.submission.gallery;
          var pictures = [];
          for (var i in gallery) {
            if (gallery[i]) {
              if (mode === "admin") {
                pictures.push(baseFileUrl + gallery[i].id);
              } else {
                pictures.push(gallery[i].uri);
              }
            }
          }
          return pictures;
        };
      },
      controllerAs: 'ctrl'
    };
  });

  ngModule.directive('galleryForm', ['$templateCache', '$http', '$mdDialog', function($templateCache, $http, $mdDialog) {
    return {
      restrict: 'E'
      , template: $templateCache.get('wfm-template/gallery-form.tpl.html')
      , controller: function($scope) {
        var self = this;
        var fileManagerClient = {
          upload: function(uri, formData) {
            return $http({
              url: uri,
              method: 'POST',
              headers: {
                'Content-Type': undefined
              },
              data: formData
            });
          },
          download: function(uri) {
            return $http({
              method: 'GET',
              url: uri
            });
          }
        };

        getServerUrl($fh).then(function(serverBaseUrl) {
          var url = new URL('/file/', serverBaseUrl);
          self.fileManager = new FileManager(url.toString(), 'gallery', fileManagerClient);
          self.camera = new Camera(cameraOptionsBuilder);
        });

        self.model = {};
        self.parentController = $scope.$parent;
        self.back = function(event) {
          self.parentController.ctrl.triggerBackStep(self.model);
          event.preventDefault();
          event.stopPropagation();
        };
        self.done = function(event) {
          self.parentController.ctrl.triggerCompleteStep(self.model);
          event.preventDefault();
          event.stopPropagation();
        };

        self.addImage = function(uri, id) {
          $scope.$apply(function() {
            self.model.gallery = self.model.gallery || [];
            self.model.gallery.push({ uri: uri, id: id });
          });
        };

        self.takePicture = function() {
          if (!window.navigator.camera) {
            var alert = $mdDialog.alert({
              title: 'Camera not available in browser',
              textContent: 'Camera plugin not available. Try running project in emulator or using `cordova run browser`.',
              ok: 'Close'
            });
            return $mdDialog.show(alert);
          }
          self.camera.capture().then(function(captureResponse) {
            captureResponse.id = uuid.create().toString();
            self.addImage(captureResponse.value, captureResponse.id);
            return captureResponse;
          }).then(function(captureResponse) {
            var file = {
              uri: captureResponse.value,
              type: captureResponse.type,
              id: captureResponse.id
            };
            return self.fileManager.scheduleFileToBeUploaded(file);
          }).catch(console.error);
        };
      }
      , controllerAs: 'ctrl'
    };
  }]);

  return moduleName;
}
801303
function upload(file_mngr_url, file, filename, success, error) {
    // Assemble data
    var fd = new FormData();
    fd.append("filename", filename);
    fd.append("file", file);
    var req = new XMLHttpRequest();
    req.open("POST", file_mngr_url + "/upload");
    req.onload = function(e) {
        var url = JSON.parse(req.response).url;
        if (url === undefined)
            error();
        else
            success(url);
    };
    req.send(fd);
}
860062
function uploadSubmissionFile(params, cb) {
  var resourcePath = config.addURIParams("/appforms/submissions/:id/fields/:fieldId/files/:fileId", params);
  var method = "POST";
  var data = params.fileDetails;

  params.resourcePath = resourcePath;
  params.method = method;
  params.data = data;

  //Flagging This Request As A File Request
  params.fileRequest = true;
  params.fileUploadRequest = true;

  mbaasRequest.app(params, cb);
}
289552
function hotDownloadUpdateChunk(chunkId) {
		var filename = require("path").join(__dirname, $hotChunkFilename$);
		require("fs").readFile(filename, "utf-8", function(err, content) {
			if (err) {
				if ($require$.onError) return $require$.oe(err);
				throw err;
			}
			var chunk = {};
			require("vm").runInThisContext(
				"(function(exports) {" + content + "\n})",
				{ filename: filename }
			)(chunk);
			hotAddUpdateChunk(chunk.id, chunk.modules);
		});
	}
774474
function image(ph, fireErr) {
    if (arguments.length < 2) {
        fireErr = false;
    }
    var doit   = new DoIt(),
        jn     = doit.join(),
        marker = "data:image";

    if (isString(ph) && ph.length > marker.length) {
        // use "for" instead of "indexOf === 0"
        var i = 0;
        for(; i < marker.length && marker[i] === ph[i]; i++) {}

        if (i < marker.length) {
            var file = ZFS.read(ph);
            if (file !== null) {
                ph = "data:image/" + file.ext +  ";base64," + file.data;
            }
        }
    }

    $zenv.loadImage(ph,
        function(img) {
            jn(img);
        },
        function(img, e) {
            if (fireErr === true) {
                doit.error(e);
            } else {
                jn(img);
            }
        }
    );
    return doit;
}
496238
function grabImages (opts) {
  if (!opts.quiet) console.log(multiline(function () {/*

 _ _|                  |                                    |
   |    __ \     __|   __|    _` |    _` |    __|    _` |   __ \
   |    |   |  \__ \   |     (   |   (   |   |      (   |   |   |
 ___|  _|  _|  ____/  \__|  \__,_|  \__, |  _|     \__,_|  _.__/
                                    |___/

*/}))

  opts.shortcode.forEach(function (shortcode) {
    // set up the sink
    var filename = instagrab.filename(shortcode, opts.size)
    var filepath = path.join(process.cwd(), filename)
    var toFile = fs.createWriteStream(filepath)
    toFile.on('error', onSaveError(shortcode))
    toFile.on('finish', function onSaved () {
      if (this.quiet) return;
      console.log('grabbed: ', filename)
    })

    // grab the bits
    return instagrab(shortcode, opts.size)
      .on('error', onGrabError(shortcode))
      .pipe(toFile)
  })
}
874020
function uploadExample() {
  return upload('./files/small.mp4', 0, {
    onBegin: () => console.log('begin'),
    onProgress: ({ loaded, total }) => console.log(loaded, total, (loaded / total * 100).toFixed(2) + '%')
  }).then((result) => {
    console.log("Done");
    return result;
  });
}
607346
async function upload(localFiles, options, onProgess){

    // the index of the current uploaded file
    let fileUploadIndex = 0;

    async function uploadFile(localFile, remoteFilename){

        // increment upload index
        fileUploadIndex++;

        // get file stats
        try{
            const stats = await _fs.statx(localFile);

            // check if file is directory
            if (stats.isDirectory()) {
                _mculogger.error('Path "' + localFile + '" is a directory.');
                return;
            }

        // local file available
        }catch (err){
            _logger.error('Local file not found "' + localFile + '" skipping...');
            _logger.debug(err);
            return;
        }

        // display filename
        _logger.log('Uploading "' + localFile + '" >> "' + remoteFilename + '"...');

        // normalize the remote filename (strip relative parts)
        remoteFilename = remoteFilename.replace(/\.\.\//g, '').replace(/\.\./g, '').replace(/^\.\//, '');

        // delete old file (may existent)
        await _nodeMcuConnector.remove(remoteFilename);

        // start file transfer
        await _nodeMcuConnector.upload(localFile, remoteFilename, options, function(current, total){
            // proxy and append file-number
            onProgess(current, total, fileUploadIndex);
        });

        // compile flag set ? and is a lua file ?
        if (options.compile && _path.extname(localFile).toLowerCase() == '.lua'){
            _mculogger.log(' |- compiling lua file..');

            await _nodeMcuConnector.compile(remoteFilename);
            _mculogger.log(' |- success');

            // drop original lua file
            await _nodeMcuConnector.remove(remoteFilename);
            _mculogger.log(' |- original Lua file removed');
        }
    }

    // try to establish a connection to the module
    await getConnection();

    // single file upload ?
    if (localFiles.length == 1){
        // extract first element
        const localFile = localFiles[0];

        // filename defaults to original filename minus path.
        // this behaviour can be overridden by --keeppath and --remotename options
        const remoteFile = options.remotename ? options.remotename : (options.keeppath ? localFile : _path.basename(localFile));

        // start single file upload
        await uploadFile(localFile, remoteFile);

        // log message
        _logger.log('File Transfer complete!');

        // run file ?
        if (options.run === true){
            await run(remoteFile);
        }

    // bulk upload ?
    }else{

        // file available ?
        while (localFiles.length > 0){
             // extract file
             const localFile = localFiles.shift();

             // keep-path option set ?
             const remoteFile = (options.keeppath ? localFile : _path.basename(localFile));

             // trigger upload
             await uploadFile(localFile, remoteFile);
        }

        // log message
        _logger.log('Bulk File Transfer complete!');
    }
}
58530
function (file, responseText) {
        console.log(responseText); // console should show the ID you pointed to
        // read the upload path from the elements data-upload attribute.
        var uploadPath = $(this.dropzone.element).data("upload") + responseText;
        var linkToUploadedFile = "(" + uploadPath + ")";
        if ( file.type.startsWith( "image/" ) ) {
            linkToUploadedFile = "![]" + linkToUploadedFile;
        } else {
            linkToUploadedFile = "[" + responseText + "]" + linkToUploadedFile;
        }
        this.simplemde.value(this.simplemde.value() + "\n" + linkToUploadedFile + "\n");
    }
1374926
function dataURLtoBlob(dataUrl) {
    let pos = dataUrl.indexOf(',', 0)
    let arr = [ dataUrl.slice(0, pos), dataUrl.slice(pos+1) ]
    let mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while(n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([ u8arr ], { type:mime })
}
274571
function CodepenDataAdapter() {

    // The following URL's need to use `localhost` as these values get replaced during release
    var CORE_JS  = 'http://localhost:8080/angular-material.js';
    var CORE_CSS = 'http://localhost:8080/angular-material.css';
    var DOC_CSS  = 'http://localhost:8080/docs.css';              // CSS overrides for custom docs

    var LINK_FONTS_ROBOTO = '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">';

    var UNSECURE_CACHE_JS = 'http://ngmaterial.assets.s3.amazonaws.com/svg-assets-cache.js';
    var ASSET_CACHE_JS = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/svg-assets-cache.js';


    return {
      translate: translate
    };

    // Translates a demo model to match Codepen's post data
    // See http://blog.codepen.io/documentation/api/prefill
    function translate(demo, externalScripts) {
      var files = demo.files;

      return appendLicenses({
        title: demo.title,
        html: processHtml(demo),
        head: LINK_FONTS_ROBOTO,

        js: processJs(files.js),
        css: mergeFiles(files.css).join(' '),

        js_external: externalScripts.concat([ASSET_CACHE_JS, CORE_JS]).join(';'),
        css_external: [CORE_CSS, DOC_CSS].join(';')
      });
    }

    // Modifies index.html with necessary changes in order to display correctly in codepen
    // See each processor to determine how each modifies the html
    function processHtml(demo) {

      var allContent = demo.files.index.contents;

      var processors = [
        applyAngularAttributesToParentElement,
        insertTemplatesAsScriptTags,
        htmlEscapeAmpersand
      ];

      processors.forEach(function(processor) {
        allContent = processor(allContent, demo);
      });

      return allContent;
    }

    /**
     * Append MIT License information to all CodePen source samples(HTML, JS, CSS)
     */
    function appendLicenses(data) {

      data.html = appendLicenseFor(data.html, 'html');
      data.js   = appendLicenseFor(data.js, 'js');
      data.css  = appendLicenseFor(data.css, 'css');

      function appendLicenseFor(content, lang) {
            var commentStart = '', commentEnd = '';

        switch (lang) {
          case 'html' : commentStart = '<!--'; commentEnd = '-->'; break;
          case 'js'   : commentStart = '/**';  commentEnd = '**/'; break;
          case 'css'  : commentStart = '/*';   commentEnd = '*/';  break;
        }

        return content + '\n\n'+
          commentStart + '\n'+
          'Copyright 2018 Google LLC. All Rights Reserved. \n'+
          'Use of this source code is governed by an MIT-style license that can be found\n'+
          'in the LICENSE file at http://material.angularjs.org/HEAD/license.\n'+
          commentEnd;
      }

      return data;
    }


    // Applies modifications the javascript prior to sending to codepen.
    // Currently merges js files and replaces the module with the Codepen
    // module.  See documentation for replaceDemoModuleWithCodepenModule.
    function processJs(jsFiles) {
      var mergedJs = mergeFiles(jsFiles).join(' ');
      var script = replaceDemoModuleWithCodepenModule(mergedJs);
      return script;
    }

    // Maps file contents to an array
    function mergeFiles(files) {
      return files.map(function(file) {
        return file.contents;
      });
    }

    // Adds class to parent element so that styles are applied correctly
    // Adds ng-app attribute.  This is the same module name provided in the asset-cache.js
    function applyAngularAttributesToParentElement(html, demo) {
      var tmp;

      // Grab only the DIV for the demo...
      angular.forEach(angular.element(html), function(it,key){
        if ((it.nodeName != "SCRIPT") && (it.nodeName != "#text")) {
          tmp = angular.element(it);
        }
      });

      tmp.addClass(demo.id);
      tmp.attr('ng-app', 'MyApp');
      return tmp[0].outerHTML;
    }

    // Adds templates inline in the html, so that templates are cached in the example
    function insertTemplatesAsScriptTags(indexHtml, demo) {
      if (demo.files.html.length) {
        var tmp = angular.element(indexHtml);
        angular.forEach(demo.files.html, function(template) {
          tmp.append("<script type='text/ng-template' id='" +
                     template.name + "'>" +
                     template.contents +
                     "</script>");
        });
        return tmp[0].outerHTML;
      }
      return indexHtml;
    }

    // Escapes ampersands so that after codepen unescapes the html the escaped code block
    // uses the correct escaped characters
    function htmlEscapeAmpersand(html) {
      return html
        .replace(/&/g, "&amp;");
    }

    // Required to make codePen work. Demos define their own module when running on the
    // docs site.  In order to ensure the codepen example can use the svg-asset-cache.js, the
    // module needs to match so that the $templateCache is populated with the necessary
    // assets.

    function replaceDemoModuleWithCodepenModule(file) {
      var matchAngularModule =  /\.module\(('[^']*'|"[^"]*")\s*,(\s*\[([^\]]*)\]\s*\))/ig;
      var modules = "['ngMaterial', 'ngMessages', 'material.svgAssetsCache']";

      // See scripts.js for list of external AngularJS libraries used for the demos

      return file.replace(matchAngularModule, ".module('MyApp', "+ modules + ")");
    }
  }
285803
function (data) {
          //If a token is not configured, don't do anything.
          if (!token) {
            return;
          }

          //TODO we're injecting this here to resolve circular dependency issues.  Is this safe?
          var $location = $injector.get( '$location' );

          lastLog = new Date();

          var sentData = angular.extend({}, extra, data);

          if (includeCurrentUrl) {
            sentData.url = $location.absUrl()
          }

          if( includeTimestamp ) {
            sentData.timestamp = lastLog.toISOString();
          }

          //Loggly's API doesn't send us cross-domain headers, so we can't interact directly
          new Image().src = buildUrl(sentData);
        }