Upload an import file.
558520
public RESTImportTaskList uploadFile(Integer importJobId, File file, String sourceSrs) throws Exception {

        LOG.debug("Uploading file " + file.getName() + " to import job " + importJobId);

        Response httpResponse = HttpUtil.post(
            this.addEndPoint(importJobId + "/tasks"),
            file,
            this.username,
            this.password
        );

        HttpStatus responseStatus = httpResponse.getStatusCode();
        if (responseStatus == null || !responseStatus.is2xxSuccessful()) {
            throw new GeoServerRESTImporterException("Error while uploading the file.");
        }

        LOG.debug("Successfully uploaded the file to import job " + importJobId);

        RESTImportTaskList importTaskList = null;
        // check, if it is a list of import tasks (for multiple layers)
        try {
            importTaskList = mapper.readValue(httpResponse.getBody(), RESTImportTaskList.class);
            LOG.debug("Imported file " + file.getName() + " contains data for multiple layers.");
            return importTaskList;
        } catch (Exception e) {
            LOG.debug("Imported file " + file.getName() + " likely contains data for single " +
                "layer. Will check this now.");
            try {
                RESTImportTask importTask = mapper.readValue(httpResponse.getBody(), RESTImportTask.class);
                if (importTask != null) {
                    importTaskList = new RESTImportTaskList();
                    importTaskList.add(importTask);
                    LOG.debug("Imported file " + file.getName() + " contains data for a single layer.");
                }
                return importTaskList;
            } catch (Exception ex) {
                LOG.info("It seems that the SRS definition source file can not be interpreted by " +
                    "GeoServer / GeoTools. Try to set SRS definition to " + sourceSrs + ".");

                File updatedGeoTiff = null;
                try {
                    if (!StringUtils.isEmpty(sourceSrs)) {
                        // "First" recursion: try to add prj file to ZIP.
                        updatedGeoTiff = addPrjFileToArchive(file, sourceSrs);
                    } else {
                        // At least second recursion: throw exception since SRS definition
                        // could not be set.
                        throw new GeoServerRESTImporterException("Could not set SRS definition "
                            + "of GeoTIFF.");
                    }
                } catch (ZipException ze) {
                    throw new GeoServerRESTImporterException("No valid ZIP file given containing "
                        + "GeoTiff datasets.");
                }

                if (updatedGeoTiff != null) {
                    importTaskList = uploadFile(importJobId, updatedGeoTiff, null);
                    return importTaskList;
                }
            }
        }

        return null;
    }
608973
def upload_file(upload_url, upload_fields, filepath, callback=None):
    """"""
    upload_fields = list(six.iteritems(upload_fields))
    upload_fields.append(
        ("file", (os.path.basename(filepath), click.open_file(filepath, "rb")))
    )
    encoder = MultipartEncoder(upload_fields)
    monitor = MultipartEncoderMonitor(encoder, callback=callback)

    config = cloudsmith_api.Configuration()
    if config.proxy:
        proxies = {"http": config.proxy, "https": config.proxy}
    else:
        proxies = None

    headers = {"content-type": monitor.content_type}

    client = get_files_api()
    headers["user-agent"] = client.api_client.user_agent

    session = create_requests_session()
    resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies)

    try:
        resp.raise_for_status()
    except requests.RequestException as exc:
        raise ApiException(
            resp.status_code, headers=exc.response.headers, body=exc.response.content
        )
925017
def upload(file_path, dataset=None, public=False):
    """"""

    config = ApiConfig()
    client = ApiClient(config.host, config.app_id, config.app_secret)
    return client.upload(file_path, dataset, public)
579636
def create(self, filename, filedata):
        """"""
        attributes = {'filename': filename,
                      'source': filedata}
        return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data')
110143
def upload_file(
        self,
        filename,
        upload_as=None,
        blocksize=None,
        callback=None,
        information_callback=None,
        allow_timeout=False,
    ):
        """"""

        with delayed_close(
            filename if hasattr(filename, "read") else open(filename, "rb")
        ) as file:
            filename = upload_as or os.path.split(filename)[1]
            try:
                file.seek(0, 2)
                if file.tell() > self.config.max_file:
                    raise ValueError(
                        f"File must be at most {self.config.max_file >> 30} GB"
                    )
            finally:
                try:
                    file.seek(0)
                except Exception:
                    pass

            files = Data(
                {"file": {"name": filename, "value": file}},
                blocksize=blocksize,
                callback=callback,
            )

            headers = {"Origin": BASE_URL}
            headers.update(files.headers)

            while True:
                key, server, file_id = self._generate_upload_key(
                    allow_timeout=allow_timeout
                )
                info = dict(
                    key=key,
                    server=server,
                    file_id=file_id,
                    room=self.room_id,
                    filename=filename,
                    len=files.len,
                    resumecount=0,
                )
                if information_callback:
                    if information_callback(info) is False:
                        continue
                break

            params = {"room": self.room_id, "key": key, "filename": filename}

            if self.key:
                params["roomKey"] = self.key
            if self.password:
                params["password"] = self.password

            while True:
                try:
                    post = self.conn.post(
                        f"https://{server}/upload",
                        params=params,
                        data=files,
                        headers=headers,
                    )
                    post.raise_for_status()
                    break

                except requests.exceptions.ConnectionError as ex:
                    if "aborted" not in repr(ex):  # ye, that's nasty but "compatible"
                        raise
                    try:
                        resume = self.conn.get(
                            f"https://{server}/rest/uploadStatus",
                            params={"key": key, "c": 1},
                        ).text
                        resume = from_json(resume)
                        resume = resume["receivedBytes"]
                        if resume <= 0:
                            raise ConnectionError("Cannot resume")
                        file.seek(resume)
                        files = Data(
                            {"file": {"name": filename, "value": file}},
                            blocksize=blocksize,
                            callback=callback,
                            logical_offset=resume,
                        )
                        headers.update(files.headers)
                        params["startAt"] = resume
                        info["resumecount"] += 1
                        if information_callback:
                            information_callback(info)
                    except requests.exceptions.ConnectionError as iex:
                        # ye, that's nasty but "compatible"
                        if "aborted" not in repr(iex):
                            raise
                        continue  # another day, another try
            return file_id
62181
def upload_file(client, bucket, local_path, remote_path, overwrite=False):
    """"""
    bucket = client.get_bucket(bucket)
    blob = storage.Blob(remote_path, bucket)
    if (not overwrite) and blob.exists():
        raise Conflict('File/object already exists on the bucket!')
    blob.upload_from_filename(local_path)
275724
public function ImportFromClientForm() {
        if(!Permission::check('ADMIN')) {
            Security::permissionFailure($this);
            return;
        }
        
        $uploadField=new FileField('ImportFile', _t('CodeBank.EXPORT_FILE', '_Client Export File'));
        $uploadField->getValidator()->setAllowedExtensions(array('cbexport'));
        File::config()->allowed_extensions=array('cbexport');
        
        
        $fields=new FieldList(
                            new LiteralField('ImportWarning', '<p class="message warning">'._t('CodeBank.IMPORT_DATA_WARNING', '_Warning clicking import will erase all snippets in the database, it is recommended you backup your database before proceeding').'</p>'),
                            new TabSet('Root',
                                                new Tab('Main',
                                                                $uploadField,
                                                                new CheckboxField('AppendData', _t('CodeBank.APPEND_IMPORT', '_Import and Append Data (keep your existing data however appending may cause duplicates)'))
                                                            )
                                            )
                        );
        
        $actions=new FieldList(
                            FormAction::create('doImportData', _t('CodeBank.IMPORT', '_Import'))->addExtraClass('ss-ui-button ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true)
                        );
        
        
        $validator=new RequiredFields(
                                    'ImportFile'
                                );
        
        
        $form=new Form($this, 'ImportFromClientForm', $fields, $actions, $validator);
        $form->addExtraClass('member-profile-form');
        
        return $form;
    }
204898
def file_upload(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/upload' % object_id, input_params, always_retry=always_retry, **kwargs)
577896
def ImportFile(store, filename, start):
  """"""
  with io.open(filename, "r") as fp:
    reader = csv.Reader(fp.read())
    i = 0
    current_row = None
    product_code_list = []
    op_system_code_list = []
    for row in reader:
      # Skip first row.
      i += 1
      if i and i % 5000 == 0:
        data_store.DB.Flush()
        print("Imported %d hashes" % i)
      if i > 1:
        if len(row) != 8:
          continue
        try:
          if i < start:
            continue
          if current_row:
            if current_row[0] == row[0]:
              # Same hash, add product/system
              product_code_list.append(int(row[5]))
              op_system_code_list.append(row[6])
              continue
            # Fall through and add current row.
          else:
            # First row.
            current_row = row
            product_code_list = [int(row[5])]
            op_system_code_list = [row[6]]
            continue
          _ImportRow(store, current_row, product_code_list, op_system_code_list)
          # Set new hash.
          current_row = row
          product_code_list = [int(row[5])]
          op_system_code_list = [row[6]]
        except Exception as e:  # pylint: disable=broad-except
          print("Failed at %d with %s" % (i, str(e)))
          return i - 1
    if current_row:
      _ImportRow(store, current_row, product_code_list, op_system_code_list)
    return i
190681
public function upload()
    {
        if ($newFile = $this->getNewFileName()){
            $origin = $destination = \Devil::getPathOf($this->config['dest']);
            $this->remove();
            if (isset($this->config['onload'])) {
                $destination .= '/origin';
            }
            if (!is_dir($destination)) mkdir ($destination, 0777, true);
            $realFileName = $destination . '/' . $this->_primaryKey . '_' . $this->getNewFileName();
            if (move_uploaded_file($this->uploaded['tmp_name'], $realFileName)) {
                if (isset($this->config['onload'])) foreach ($this->config['onload'] as $method=>$config) {
                    $this->$method($realFileName, $origin, $config, $this->_primaryKey . '_' . $this->getNewFileName());
                }
            }
        }
    }
850426
async def _upload_chunks(
            cls, rfile: BootResourceFile, content: io.IOBase, chunk_size: int,
            progress_callback=None):
        """"""
        content.seek(0, io.SEEK_SET)
        upload_uri = urlparse(
            cls._handler.uri)._replace(path=rfile._data['upload_uri']).geturl()
        uploaded_size = 0

        insecure = cls._handler.session.insecure
        connector = aiohttp.TCPConnector(verify_ssl=(not insecure))
        session = aiohttp.ClientSession(connector=connector)

        async with session:
            while True:
                buf = content.read(chunk_size)
                length = len(buf)
                if length > 0:
                    uploaded_size += length
                    await cls._put_chunk(session, upload_uri, buf)
                    if progress_callback is not None:
                        progress_callback(uploaded_size / rfile.size)
                if length != chunk_size:
                    break
102380
def upload():
    """"""
    try:
        o = check_output(['twine', 'upload'] + glob('dist/*'))
    except CalledProcessError:
        call(['twine', 'upload'] + glob('dist/*'))
        raise
    print(o.decode('utf-8'))
507613
function import_file()
    {
        $uid     = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
        $mbox    = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
        $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
        $storage = $this->rc->get_storage();
        $engine  = $this->enigma->load_engine();

        if ($uid && $mime_id) {
            // Note: we get the attachment body via rcube_message class
            // to support keys inside encrypted messages (#5285)
            $message = new rcube_message($uid, $mbox);

            // Check if we don't need to ask for password again
            foreach ($engine->decryptions as $status) {
                if ($status instanceof enigma_error) {
                    if ($status->getCode() == enigma_error::BADPASS) {
                        $this->password_prompt($status, array(
                                'input_uid'    => $uid,
                                'input_mbox'   => $mbox,
                                'input_part'   => $mime_id,
                                'input_task'   => 'mail',
                                'input_action' => 'plugin.enigmaimport',
                                'action'       => '?',
                                'iframe'       => true,
                        ));
                        $this->rc->output->send($this->rc->output->type == 'html' ? 'iframe' : null);
                        return;
                    }
                }
            }

            if ($engine->is_keys_part($message->mime_parts[$mime_id])) {
                $part = $message->get_part_body($mime_id);
            }
        }

        if ($part && is_array($result = $engine->import_key($part))) {
            $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation',
                array('new' => $result['imported'], 'old' => $result['unchanged']));
        }
        else {
            $this->rc->output->show_message('enigma.keysimportfailed', 'error');
        }

        $this->rc->output->send($this->rc->output->type == 'html' ? 'iframe' : null);
    }
1368042
def Upload(self,directory,filename):
        """"""

        db = self._loadDB(directory)

        logger.debug("wp: Attempting upload of %s"%(filename))

        # See if this already exists in our DB
        if db.has_key(filename):
            pid=db[filename]
            logger.debug('wp: Found %s in DB with post id %s'%(filename,pid))
        else:
            pid=None

        fullfile=os.path.join(directory,filename)

        fid=open(fullfile,'r');

        # Read meta data and content into dictionary
        post=self._readMetaAndContent(fid)

        #Connect to WP
        self._connectToWP()

        # If no pid, it means post is fresh off the press
        # and not uploaded yet!
        if not pid:
            # Get a PID by uploading
            pid=self.wp.call(NewPost(post))
            if pid:
                logger.debug("wp: Uploaded post with pid %s",pid)
                db[filename]=pid
                self._saveDB(directory,db)
                return True
            else:
                logger.error("wp: Couldn't upload post")
                return False
        else:
            # Already has PID, replace post
            logger.debug("wp: Replacing post with pid %s",pid)
            #FIXME: Check return value?!
            self.wp.call(EditPost(pid,post))
            return True

        return False
361929
def upload(self):
    """"""
    if not self._converter:
      raise RuntimeError(
          'Must set _converter on subclass or via set_converter before calling '
          'upload.')

    if not self.credentials:
      raise RuntimeError('Must provide credentials to use upload callback.')

    def upload_callback(test_record_obj):
      proto = self._convert(test_record_obj)
      self.upload_result = send_mfg_inspector_data(
          proto, self.credentials, self.destination_url)

    return upload_callback
243347
def stage_import_from_file(self, fd, filename='upload.gz'):
        
        schema = ImportSchema()
        resp = self.service.post(self.base,
                                 files={'file': (filename, fd)})
        return self.service.decode(schema, resp)
914186
def upload_file(self, file_name, file_obj, *args, **kwargs):
		
		previous_path = self.session_path()
		try:
			self.session_path(file_name)
			with open(self.full_path(), mode='wb') as f:
				chunk = file_obj.read(io.DEFAULT_BUFFER_SIZE)
				while len(chunk) > 0:
					f.write(chunk)
					chunk = file_obj.read(io.DEFAULT_BUFFER_SIZE)
		finally:
			self.session_path(previous_path)