A method for uploading a single file
504922
function ftpPut(inFilename, cb) {
    var fileUrl = '';
    if (/\//.test(inFilename)) {
      fileUrl = inFilename;
      inFilename = inFilename.split('/').slice(-1)[0];
    } else {
      fileUrl = localRoot + path.sep + currPath + path.sep + inFilename;
    }
    var fileData = fs.readFileSync(fileUrl);
    ftp.put(inFilename, fileData, function(err) {
      if (err) {
        log.error('Cannot upload file: ' + inFilename + ' --> ' + err);
        cb(err);
      } else {
        log.ok('Uploaded file: ' + inFilename.green + ' to: ' + ('/' + remoteRoot + '/' + currPath).yellow);
        cb(null);
      }
    });
  }
813965
def upload_file_mp(self, container, src_file_path, dst_name=None,
                       content_type=None):
        """"""
        if not os.path.exists(src_file_path):
            raise RuntimeError('file not found: ' + src_file_path)
        if not dst_name:
            dst_name = os.path.basename(src_file_path)
        if not content_type:
            content_type = "application/octet.stream"
        url = self.make_url(container, None, None)
        headers = self._base_headers
        with open(src_file_path, 'rb') as up_file:
            files = {'file': (dst_name, up_file, content_type)}
            try:
                rsp = requests.post(url, headers=headers, files=files,
                                    timeout=self._timeout)
            except requests.exceptions.ConnectionError as e:
                RestHttp._raise_conn_error(e)

        return self._handle_response(rsp)
1029488
public void createFileUploadHandler(File file) {

		final String uuid = file.getProperty(GraphObject.id);

		uploads.put(uuid, new FileUploadHandler(file));

	}
21992
@Override
	public boolean upload(String path, File file) {
		Assert.notNull(file, "file to upload is null !");
		return upload(path, file.getName(), file);
	}
799949
def upload_file(self, filepath, overwrite=True):
        """"""
        method = 'POST'
        filename = os.path.split(filepath)[1]
        endpoint = '/rest/v1/storage/{}/{}?overwrite={}'.format(
            self.client.sauce_username, filename, "true" if overwrite else "false")
        with open(filepath, 'rb') as filehandle:
            body = filehandle.read()
        return self.client.request(method, endpoint, body,
                                   content_type='application/octet-stream')
1320300
def _upload_files(item, files, upload_kwargs, prev_identifier=None, archive_session=None):
    """"""
    responses = []
    if (upload_kwargs['verbose']) and (prev_identifier != item.identifier):
        print('{0}:'.format(item.identifier))

    try:
        response = item.upload(files, **upload_kwargs)
        responses += response
    except HTTPError as exc:
        responses += [exc.response]
    finally:
        # Debug mode.
        if upload_kwargs['debug']:
            for i, r in enumerate(responses):
                if i != 0:
                    print('---')
                headers = '\n'.join(
                    [' {0}:{1}'.format(k, v) for (k, v) in r.headers.items()]
                )
                print('Endpoint:\n {0}\n'.format(r.url))
                print('HTTP Headers:\n{0}'.format(headers))
                return responses

        # Format error message for any non 200 responses that
        # we haven't caught yet,and write to stderr.
        if responses and responses[-1].status_code and responses[-1].status_code != 200:
            if not responses[-1].status_code:
                return responses
            filename = responses[-1].request.url.split('/')[-1]
            try:
                msg = get_s3_xml_text(responses[-1].content)
            except:
                msg = responses[-1].content
            print(' error uploading {}: {}'.format(filename, msg), file=sys.stderr)

    return responses
576670
protected void uploadFile() {

        hideOkAndUploadButtons();
        CmsUploader uploader = new CmsUploader();
        CmsFileInfo info = m_fileInput.getFiles()[0];
        info.setOverrideFileName(CmsResource.getName(m_replaceInfo.getSitepath()));
        uploader.uploadFiles(
            CmsCoreProvider.get().link(I_CmsUploadConstants.UPLOAD_ACTION_JSP_URI),
            CmsResource.getFolderPath(m_replaceInfo.getSitepath()),
            false,
            Collections.singletonList(info),
            Collections.<String> emptyList(),
            this);
        showProgress();
    }
872981
function uploadFile(file, next) {
    var uploadErr;

    self.uploadFile({
      source: file.source,
      target: file.target,
      server: options.server,
      keys: options.keys,
      tunnel: options.tunnel,
      remoteUser: options.remoteUser
    }).on('error', function (err) {
      if (!uploadErr) {
        uploadErr = true;
        next(err);
      }
    }).on('complete', function () {
      if (!uploadErr) {
        next();
      }
    });
  }
1268582
def upload_masterfile(element_key, file, original_filename)
      # file, elementkey , name??
      content_length = file.size
      content_type = 'application/octet-stream; charset=utf-8'
      parameter = { basic_auth: @auth,
                    headers: { 'Content-Type' => content_type,
                               'Content-Length' => content_length.to_s,
                               'storageType' => 'MASTER',
                               'filename' => original_filename.to_s },
                    body: file.read }
      upload_file element_key, parameter
    end
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
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)
219602
def _request(self, method, url, params=None, uploads=None):
        
        c = pycurl.Curl()

        if method == self.POST:
            c.setopt(c.POST, 1)
            if uploads is not None:
                if isinstance(uploads, dict):
                    # handle single upload
                    uploads = [uploads]
                for upload in uploads:
                    params += [(upload['field'],
                               (c.FORM_FILE, upload['path']))]

                c.setopt(c.HTTPPOST, params)
            else:
                # XXX memory leak in pyCurl/7.29.0?
                data = urllib.urlencode(params)
                c.setopt(c.POSTFIELDS, data)

        elif method == self.GET:
            c.setopt(c.HTTPGET, 1)
            if params:
                url += '?%s' % urllib.urlencode(params)

        elif method == self.DELETE:
            c.setopt(pycurl.CUSTOMREQUEST, self.DELETE)

        else:
            raise NotSupportedError(str(method))

        buffer = []

        def _write_cb(data):
            buffer.append(data)

        c.setopt(c.HTTPHEADER, self._hook_header(params))
        c.setopt(pycurl.SSL_VERIFYPEER, 0)
        c.setopt(pycurl.SSL_VERIFYHOST, 0)
        c.setopt(c.URL, url)
        c.setopt(c.NOPROGRESS, 0)
        c.setopt(c.PROGRESSFUNCTION, self._updated_cb)
        c.setopt(c.WRITEFUNCTION, _write_cb)
        c.setopt(c.FOLLOWLOCATION, 1)
        #c.setopt(c.VERBOSE, True)

        try:
            self.emit('started')
            c.perform()
        except pycurl.error, e:
            raise TransferError(str(e))
        else:
            code = c.getinfo(c.HTTP_CODE)
            if not 200 <= code < 300:
                raise ResponseError(code)
        finally:
            c.close()

        return ''.join(buffer)
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!');
    }
}
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();
}
220939
def upload_file(self, file_name, file_obj, *args, **kwargs):
		
		self.dav_client().upload_to(file_obj, self.join_path(self.session_path(), file_name))
974078
def request_upload_token(self, file):
        
        self.kwargs['name'] = os.path.basename(file.name)
        self.kwargs['size'] = os.fstat(file.fileno()).st_size

        response = self._requester.request(
            'POST',
            self.url,
            _kwargs=combine_kwargs(**self.kwargs)
        )

        return self.upload(response, file)
1105149
public String uploadFile(UploadFileRequest request) throws AbstractCosException {
		request.check_param();

		String localPath = request.getLocalPath();
		long fileSize = 0;
		try {
			fileSize = CommonFileUtils.getFileLength(localPath);
		} catch (Exception e) {
			throw new UnknownException(e.toString());
		}

		long suitSingleFileSize = 8 * 1024 * 1024;
		if (fileSize < suitSingleFileSize) {
			return uploadSingleFile(request);
		} else {
			UploadSliceFileRequest sliceRequest = new UploadSliceFileRequest(request);
			sliceRequest.setInsertOnly(request.getInsertOnly());
			return uploadSliceFile(sliceRequest);
		}
	}