Upload Working with 5.3
185143
public function upload(Request $request)
    {
        try {
            $path = $request->file->store($request->upload_path, $this->filesystem);
            $success = true;
            $message = 'Successfully uploaded new file!';
        } catch (Exception $e) {
            $success = false;
            $message = $e->getMessage();
        }

        $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix().$path;
        Image::make($realPath)->orientate()->save();

        $path = preg_replace('/^public\//', '', $path);

        return response()->json(compact('success', 'message', 'path'));
    }
1202074
def _upload(self, obj_name, content, content_type, content_encoding,
            content_length, etag, chunked, chunk_size, headers):
        
        if content_type is not None:
            headers["Content-Type"] = content_type
        if content_encoding is not None:
            headers["Content-Encoding"] = content_encoding
        if isinstance(content, six.string_types):
            fsize = len(content)
        else:
            if chunked:
                fsize = None
            elif content_length is None:
                fsize = get_file_size(content)
            else:
                fsize = content_length
        if fsize is None or fsize <= MAX_FILE_SIZE:
            # We can just upload it as-is.
            return self._store_object(obj_name, content=content, etag=etag,
                    chunked=chunked, chunk_size=chunk_size, headers=headers)
        # Files larger than MAX_FILE_SIZE must be segmented
        # and uploaded separately.
        num_segments = int(math.ceil(float(fsize) / MAX_FILE_SIZE))
        digits = int(math.log10(num_segments)) + 1
        # NOTE: This could be greatly improved with threading or other
        # async design.
        for segment in range(num_segments):
            sequence = str(segment + 1).zfill(digits)
            seg_name = "%s.%s" % (obj_name, sequence)
            with utils.SelfDeletingTempfile() as tmpname:
                with open(tmpname, "wb") as tmp:
                    tmp.write(content.read(MAX_FILE_SIZE))
                with open(tmpname, "rb") as tmp:
                    # We have to calculate the etag for each segment
                    etag = utils.get_checksum(tmp)
                    self._store_object(seg_name, content=tmp, etag=etag,
                            chunked=False, headers=headers)
        # Upload the manifest
        headers.pop("ETag", "")
        headers["X-Object-Manifest"] = "%s/%s." % (self.name, obj_name)
        self._store_object(obj_name, content=None, headers=headers)
1261621
function uploadFile(file) {
  var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _lodash2.default.noop;

  // const upload = new Upload(file);
  // upload.on('end', res => {
  //   console.log(res);
  // });
  // const options = {
  //   path: window.UPLOAD_PATH || '/api/uploads/',
  // };
  // upload.to(options);

  // Create a new tus upload
  var upload = new _tusJsClient2.default.Upload(file, {
    // TODO enable resumable uploads
    resume: false,
    endpoint: window.UPLOAD_PATH || '/api/uploads/',
    onError: function onError(err) {
      console.log('upload failed:', err);
      callback(null, err);
    },
    onProgress: function onProgress(bytesUploaded, bytesTotal) {
      var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
      console.log('progress %s/%s, %s', bytesUploaded, bytesTotal, percentage + '%');
    },
    onSuccess: function onSuccess() {
      console.log('download %s from %s', upload.file.name, upload.url);
      callback({ name: upload.file.name, url: upload.url });
    }
  });

  // Start the upload
  upload.start();
}
1067952
def upload(remote_location, remotes=None, ignores=None,
           static_root="/static/", prefix="", dry_run=False):
    # pylint:disable=too-many-arguments
    
    if remotes is None:
        remotes, ignores = _resources_files(
            abs_paths=remote_location.startswith('s3://'))
    if remote_location.startswith('s3://'):
        from deployutils.s3 import S3Backend
        backend = S3Backend(remote_location,
            static_root=static_root, dry_run=dry_run)
        backend.upload(list_local(remotes, prefix), prefix)
    else:
        excludes = []
        if ignores:
            for ignore in ignores:
                excludes += ['--exclude', ignore]
        # -O omit to set mod times on directories to avoid permissions error.
        shell_command(['/usr/bin/rsync']
            + excludes + ['-pOthrRvz', '--rsync-path', '/usr/bin/rsync']
            + remotes + [remote_location], dry_run=dry_run)
333698
def upload_resumable(self, fd, filesize, filehash, unit_hash, unit_id,
                         unit_size, quick_key=None, action_on_duplicate=None,
                         mtime=None, version_control=None, folder_key=None,
                         filedrop_key=None, path=None, previous_hash=None):
        
        action = 'upload/resumable'

        headers = {
            'x-filesize': str(filesize),
            'x-filehash': filehash,
            'x-unit-hash': unit_hash,
            'x-unit-id': str(unit_id),
            'x-unit-size': str(unit_size)
        }

        params = QueryParams({
            'quick_key': quick_key,
            'action_on_duplicate': action_on_duplicate,
            'mtime': mtime,
            'version_control': version_control,
            'folder_key': folder_key,
            'filedrop_key': filedrop_key,
            'path': path,
            'previous_hash': previous_hash
        })

        upload_info = {
            "fd": fd,
            "filename": "chunk"
        }

        return self.request(action, params, action_token_type="upload",
                            upload_info=upload_info, headers=headers)
666116
def upload(self, release, filename, content_type=None):
        
        release = self.as_id(release)
        name = os.path.basename(filename)
        if not content_type:
            content_type, _ = mimetypes.guess_type(name)
        if not content_type:
            raise ValueError('content_type not known')
        inputs = {'name': name}
        url = '%s%s/%s/assets' % (self.uploads_url,
                                  urlsplit(self.api_url).path,
                                  release)
        info = os.stat(filename)
        size = info[stat.ST_SIZE]
        response = self.http.post(
            url, data=stream_upload(filename), auth=self.auth,
            params=inputs,
            headers={'content-type': content_type,
                     'content-length': str(size)})
        response.raise_for_status()
        return response.json()
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);
  });
}
1277138
def upload(self, payload=None, content_type=None):
        
        # platform - prefer the value passed in to func over config
        payload = payload or self.config.payload
        content_type = content_type or self.config.content_type

        if payload is None:
            raise ValueError('Specify a file to upload.')

        if not os.path.exists(payload):
            raise IOError('Cannot upload %s: File does not exist.' % payload)

        upload_results = client.upload(
            self.config, self.connection, payload, content_type)

        # return api response
        return upload_results
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();
    }
}
1063645
def upload_simple(self, fd, filename, folder_key=None, path=None,
                      filedrop_key=None, action_on_duplicate=None,
                      mtime=None, file_size=None, file_hash=None):
        
        action = 'upload/simple'

        params = QueryParams({
            'folder_key': folder_key,
            'path': path,
            'filedrop_key': filedrop_key,
            'action_on_duplicate': action_on_duplicate,
            'mtime': mtime
        })

        headers = QueryParams({
            'X-Filesize': str(file_size),
            'X-Filehash': file_hash,
            'X-Filename': filename.encode('utf-8')
        })

        upload_info = {
            "fd": fd,
        }

        return self.request(action, params, action_token_type="upload",
                            upload_info=upload_info, headers=headers)
609573
def upload():
    """"""
    build = g.build
    utils.jsonify_assert(len(request.files) == 1,
                         'Need exactly one uploaded file')

    file_storage = request.files.values()[0]
    data = file_storage.read()
    content_type, _ = mimetypes.guess_type(file_storage.filename)

    artifact = _save_artifact(build, data, content_type)

    db.session.add(artifact)
    db.session.commit()

    return flask.jsonify(
        success=True,
        build_id=build.id,
        sha1sum=artifact.id,
        content_type=content_type)
1200795
def _upload_media(self,directory,files=None,resize_request=None, \
            movealbum_request=None,changetitle_request=None):
        """"""
        # Connect if we aren't already
        if not self._connectToFB():
            logger.error("%s - Couldn't connect to fb")
            return False

        _megapixels=self._load_megapixels(directory)

        # Get an album ID (create album if not exists)
        _album_id,_album_name=self._get_album(directory)

        if not _megapixels:
            mpstring="original"
        else:
            mpstring=("%0.1f MP"%(_megapixels))

        # If no files given, use files from DB in dir
        if not files:
            db=self._loadDB(directory)
            files=db.keys()

        #If only one file given, make it a list
        if isinstance(files,basestring):
            files=[files]

        files.sort()

        for filename in files:

            # Get title here if any
            title=self._get_title(directory,filename)

            if title:
                print("%s - Uploading to fb, album[%s] size=%s title=%s"\
                        %(filename,_album_name,mpstring,title))
            else:
                print("%s - Uploading to fb, album[%s] size=%s"\
                        %(filename,_album_name,mpstring))

            status=self._upload_or_replace_fb(directory,filename, \
                    _album_id, _megapixels,resize_request,movealbum_request,\
                    changetitle_request,title)
            if not status:
                return False

        return True
1111707
def upload_to(instance, filename, prefix=None):
    
    ext = path.splitext(filename)[1]
    name = str(instance.pk or time()) + filename

    # We think that we use utf8 based OS file system
    filename = md5(name.encode('utf8')).hexdigest() + ext
    basedir = path.join(instance._meta.app_label, instance._meta.module_name)
    if prefix:
        basedir = path.join(basedir, prefix)
    return path.join(basedir, filename[:2], filename[2:4], filename)
1278995
def upload_files(self, file_paths, file_size_sum=0, dcp_type="data", target_filename=None,
                     use_transfer_acceleration=True, report_progress=False, sync=True):
        
        self._setup_s3_agent_for_file_upload(file_count=len(file_paths),
                                             file_size_sum=file_size_sum,
                                             use_transfer_acceleration=use_transfer_acceleration)
        pool = ThreadPool()
        if report_progress:
            print("\nStarting upload of %s files to upload area %s" % (len(file_paths), self.uuid))
        for file_path in file_paths:
            pool.add_task(self._upload_file, file_path,
                          target_filename=target_filename,
                          use_transfer_acceleration=use_transfer_acceleration,
                          report_progress=report_progress,
                          sync=sync)
        pool.wait_for_completion()
        if report_progress:
            number_of_errors = len(self.s3agent.failed_uploads)
            if number_of_errors == 0:
                print(
                    "Completed upload of %d files to upload area %s\n" %
                    (self.s3agent.file_upload_completed_count, self.uuid))
            else:
                error = "\nThe following files failed:"
                for k, v in self.s3agent.failed_uploads.items():
                    error += "\n%s: [Exception] %s" % (k, v)
                error += "\nPlease retry or contact an hca administrator at data-help@humancellatlas.org for help.\n"
                raise UploadException(error)
304992
def upgradeUpload(self, file):
        """"""
        files = {'upfile': open(file, 'rb')}
        return self.__post_files('/upgrade/upload',
                                 files=files)
1240298
def upload_file_to_s3(awsclient, bucket, key, filename):
    
    client_s3 = awsclient.get_client('s3')
    transfer = S3Transfer(client_s3)
    # Upload /tmp/myfile to s3://bucket/key and print upload progress.
    transfer.upload_file(filename, bucket, key)
    response = client_s3.head_object(Bucket=bucket, Key=key)
    etag = response.get('ETag')
    version_id = response.get('VersionId', None)
    return etag, version_id
100630
public void upload() {
    try {
      writer.flush();
      if (compress)
        zipCompress(filename);
      String remoteName = "failmon-";
      if ("true".equalsIgnoreCase(Environment.getProperty("anonymizer.hash.hostnames")))
        remoteName += Anonymizer.getMD5Hash(InetAddress.getLocalHost().getCanonicalHostName()) + "-";
      else
        remoteName += InetAddress.getLocalHost().getCanonicalHostName() + "-"; 
      remoteName += Calendar.getInstance().getTimeInMillis();//.toString();
      if (compress)
	copyToHDFS(filename + COMPRESSION_SUFFIX, hdfsDir + "/" + remoteName + COMPRESSION_SUFFIX);
      else
	copyToHDFS(filename, hdfsDir + "/" + remoteName);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // delete and re-open
    try {
      fw.close();
      fw = new FileWriter(filename);
      writer = new BufferedWriter(fw);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }