returns a function that creates a promise to upload the file to the destination
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);
    };
  }
655286
function (req, res) {
                var s3 = new AWS.S3(),
                    bucket = req.params.name,
                    key = getFullKeyParam(req.params, req.route),
                    contentType = mime.lookup(key),
                    params = {
                        Bucket: bucket,
                        Key: key,
                        // Pipe the file through the request body
                        Body: req
                    },
                    trackUploadProgress = function (evt) {
                        // This function is called each time a chunk of the file is uploaded
                        //console.log(evt);
                    },
                    handleUploadComplete = function (err, data) {
                        if (err) {
                            res.status(500).send(err);
                        } else {
                            // Add s3g link to reference the resource                            
                            data.links = [{
                                rel: 'self',
                                href: getOriginalink(req)
                            }];
                            
                            res.json(data);
                        }
                    };

				// Set content type for object if we have one
                if (contentType) {
                    params.ContentType = contentType;
                }

                s3.upload(params).on('httpUploadProgress', trackUploadProgress).send(handleUploadComplete);
            }
858868
function uploadContent(client) {
  const content = document.getElementById('file-content').value.trim();
  const key = document.getElementById('object-key-content').value.trim() || 'object';
  console.log(`content => ${key}`);

  return client.put(key, new Buffer(content)).then(res => listFiles(client));
}
1291639
function fetchFile(address, filepath) {
    return get(address)
        .then(res => new Promise((fulfill, reject) => {
            const file = fs.createWriteStream(filepath);
            res.on('error', err => {
                // reading error
                file.close();
                fs.unlink(filepath, err => {   // best effort
                    if (err) console.error(err);
                });
                reject(err);
            });
            file.on('error', err => {
                // writing error
                fs.unlink(filepath, err => {   // best effort
                    if (err) console.error(err);
                });
                reject(err);
            });
            file.on('finish', () => {
                fulfill(filepath);
            });
            res.pipe(file);
        }));
}
1363338
function downloadFile(url, outputPath) {
	const dir = path.dirname(outputPath);
	if (!fs.existsSync(dir)) {
		fs.mkdirSync(dir);
	}
	return new Promise((resolve, reject) => {
		const file = fs.createWriteStream(outputPath);
		const sendReq = request.get(url);
		sendReq.pipe(file);

		sendReq
		.on("response", (response) => {
			if (response.statusCode !== 200) {
				fs.unlink(outputPath);
				const error = new Error("Response status code was " + response.statusCode + ".");
				console.trace(error);
				reject(error);
			}
		})
		.on("error", (error) => {
			fs.unlink(outputPath);
			console.trace(error);
			reject(error);
		});

		file
		.on("finish", () => {
			file.close(() => {
				resolve();
			});
		})
		.on("error", (error) => {
			fs.unlink(outputPath);
			console.trace(error);
			reject(error);
		});
	});
}
682483
function uploadDrive(p, callback) {

		var data = {};

		// Test for DOM element
		if (p.data &&
			(typeof (HTMLInputElement) !== 'undefined' && p.data instanceof HTMLInputElement)
		) {
			p.data = {file: p.data};
		}

		if (!p.data.name && Object(Object(p.data.file).files).length && p.method === 'post') {
			p.data.name = p.data.file.files[0].name;
		}

		if (p.method === 'post') {
			p.data = {
				title: p.data.name,
				parents: [{id: p.data.parent || 'root'}],
				file: p.data.file
			};
		}
		else {

			// Make a reference
			data = p.data;
			p.data = {};

			// Add the parts to change as required
			if (data.parent) {
				p.data.parents = [{id: p.data.parent || 'root'}];
			}

			if (data.file) {
				p.data.file = data.file;
			}

			if (data.name) {
				p.data.title = data.name;
			}
		}

		// Extract the file, if it exists from the data object
		// If the File is an INPUT element lets just concern ourselves with the NodeList
		var file;
		if ('file' in p.data) {
			file = p.data.file;
			delete p.data.file;

			if (typeof (file) === 'object' && 'files' in file) {
				// Assign the NodeList
				file = file.files;
			}

			if (!file || !file.length) {
				callback({
					error: {
						code: 'request_invalid',
						message: 'There were no files attached with this request to upload'
					}
				});
				return;
			}
		}

		// Set type p.data.mimeType = Object(file[0]).type || 'application/octet-stream';

		// Construct a multipart message
		var parts = new Multipart();
		parts.append(JSON.stringify(p.data), 'application/json');

		// Read the file into a  base64 string... yep a hassle, i know
		// FormData doesn't let us assign our own Multipart headers and HTTP Content-Type
		// Alas GoogleApi need these in a particular format
		if (file) {
			parts.append(file);
		}

		parts.onready(function(body, boundary) {

			p.headers['content-type'] = 'multipart/related; boundary="' + boundary + '"';
			p.data = body;

			callback('upload/drive/v2/files' + (data.id ? '/' + data.id : '') + '?uploadType=multipart');
		});

	}
1418
function resolveFile (dir, file) {
  return new Promise((resolve, reject) => {
    resolver.resolve({}, dir, file, (err, result) => {
      if (err) reject(err)
      else resolve(result)
    })
  })
}
1312761
function uploadRouter(downloads, req, res, next) {
    if (req.originalUrl.match(/amorphic\/xhr\?path\=/) && url.parse(req.originalUrl, true).query.file && req.method === 'POST') {
        processFile(req, res, next, downloads);
    }
    else {
        next();
    }
}
1361069
function() {
          return through.obj(function(file, encode, done){
            addBefore(file.path);
            this.push(file);
            done();
          });
        }
997933
def upload(cookie, source_path, path, upload_mode):
    '''
    '''
    ondup = const.UPLOAD_ONDUP[upload_mode]
    dir_name, file_name = os.path.split(path)
    url = ''.join([
        const.PCS_URL_C,
        'file?method=upload&app_id=250528',
        '&ondup=', ondup,
        '&dir=', encoder.encode_uri_component(dir_name),
        '&filename=', encoder.encode_uri_component(file_name),
        '&', cookie.sub_output('BDUSS'),
    ])
    with open(source_path, 'rb') as fh:
        data = fh.read()
    fields = []
    files = [('file', file_name, data)]
    headers = {'Accept': const.ACCEPT_HTML, 'Origin': const.PAN_URL}
    req = net.post_multipart(url, headers, fields, files)
    if req:
        return json.loads(req.data.decode())
    else:
        return None
1317272
function readFile() {
                    return new Promise(function (resolve, reject) {
                        /** @type {?} */
                        var reader = new FileReader();
                        reader.onload = function (event) {
                            resolve(reader.result);
                        };
                        reader.onerror = function (err) {
                            reject(err);
                        };
                        reader.readAsDataURL(file);
                    });
                }
180302
function onFile(__newFile, encoding, done) {
  var buffers = [];
  var options = this.options;

  // Check the file limit
  if (options.perMaxBytes && __newFile.byteCount > options.perMaxBytes) {
    return done(new Error('The file \'' + __newFile.filename + '\' beyond size limit, only accept less than ' + options.perMaxBytes + ' bytes'));
  }

  // Check the accept content type
  if (options.acceptTypes && options.acceptTypes.indexOf(__newFile.headers['content-type']) === -1) {
    return done(new Error('Content-type of the file \'' + __newFile.filename + '\' does not accepted'));
  }

  // Determine the file descriptor-- the unique identifier.
  // Often represents the location where file should be written.
  __newFile.fd;
  var uploadDir = __newFile.fd;
  if (uploadDir.substr(0, 1) !== '/') {
    uploadDir = '/' + uploadDir;
  }

  // When then 'data' event emited, push the chunk to the buffers array.
  __newFile.on('data', function (chunk) {
    buffers.push(chunk);
  });

  // When the 'end' event emited, upload the 'buffers' to the upyun server.
  __newFile.on('end', function () {
    var buffer = Buffer.concat(buffers);
    uploadToUpyun.bind({ options })(uploadDir, buffer, __newFile, done);
  });
}
908297
function writeToFile(fileContent, filePath) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filePath, fileContent, 'utf8', (err) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(filePath);
    });
  });
}
92953
function uploadNewBackup(s3, backupTmpFilePath, bucket, key) {
  return new Promise((resolve, reject) => {
    debug(`Uploading from ${backupTmpFilePath} to ${bucket}/${key}`);

    function uploadFromStream(s3, bucket, key) {
      const pass = new stream.PassThrough();

      const params = {
        Bucket: bucket,
        Key: key,
        Body: pass
      };
      s3.upload(params, function(err, data) {
        debug('S3 upload done');
        if (err) {
          debug(err);
          reject(new VError(err, 'Upload failed'));
          return;
        }
        debug('Upload succeeded');
        debug(data);
        resolve();
      }).httpUploadProgress = (progress) => {
        debug(`S3 upload progress: ${progress}`);
      };

      return pass;
    }

    const inputStream = fs.createReadStream(backupTmpFilePath);
    const s3Stream = uploadFromStream(s3, bucket, key);
    inputStream.pipe(s3Stream);
  });
}
1246745
function FileOutputStream(istream, destinationFilename, mode=false){
    // wrap into Promise
    return new Promise(function(resolve, reject){

        // file output stream
        let ostream = null;

        // on complete - chmod
        const onComplete = function(){
            // file mode defined ?
            if (mode){
                // set mode of destination file
                _fs.chmod(destinationFilename, mode, function(err){
                    if (err){
                        reject(err);
                    }else{
                        resolve();
                    }
                });
            }else{
                // finish
                resolve();
            }
        }

        // cleanup
        const onError = function(e){
            // detach finish listener!
            if (ostream){
                ostream.removeListener('finish', onComplete);
            }
            
            // close streams
            if (istream){
                istream.destroy();
            }
            if (ostream){
                ostream.end();
            }

            // throw error
            reject(e);
        }

        // add additional error listener to input stream
        istream.on('error', onError);

        // open write stream
        ostream = _fs.createWriteStream(destinationFilename);
        ostream.on('error', onError);
        ostream.on('finish', onComplete);

        // pipe in to out
        istream.pipe(ostream);
    });
}
800155
function writeFile(namespace, fileName, fileLocation) {
  if (!gfsPromise) {
    return;
  }
  return gfsPromise.then(function(gfs) {
    var deferred = q.defer();
    var options = {
      filename: fileName
    };
    if (namespace) {
      options.root = namespace;
    }
    var writeStream = gfs.createWriteStream(options);
    writeStream.on('error', function(err) {
      console.log('An error occurred!', err);
      deferred.reject(err);
    });
    writeStream.on('close', function(file) {
      deferred.resolve(file);
    });
    fs.createReadStream(fileLocation).pipe(writeStream);
    return deferred.promise;
  });
}
476143
function upload (options, callback) {
  const promise = (
    Promise.resolve(options)
      .then(applyDefaults)
      .then(validateOptions)
      .then(opts => {
        options = opts
        return options
      })
      .then(transformOptions)
      .then(prepareRequest)
      .then(sendRequest)
      .catch(err => {
        return cleanupTempFiles(options)
          .then(() => Promise.reject(err))
      })
      .then(cleanupTempFiles)
  )
  if (callback) {
    promise
      .then(message => callback(null, message))
      .catch(err => callback(err, null))
  }
  return promise
}