Request an upload token.

        :param file: A file handler pointing to the file to upload.
        :returns: True if the file uploaded successfully, False otherwise, \
            and the JSON response from the API.
        :rtype: tuple
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)
1062405
function uploadFile(file, request, host) {
  return function(cb) {
    request
      .post(host + '/file/' + file.hash)
      .attach('data', file.abs)
      .end(function(err, res) {
        if (err) return cb(err);
        if (res.error) return cb(res.error);
        return cb();
      });
  };
}
275226
function _upload(file, options) {
		options = options || {};

		var self = this;
		var socket = this.socket;
		var chunkSize = this.chunkSize;
		var transmissionDelay = this.transmissionDelay;
		var uploadId = file.uploadId;
		var uploadTo = options.uploadTo || '';
		var data = options.data || {};
		var fileInfo = {
			id: uploadId,
			name: file.name,
			size: file.size,
			chunkSize: chunkSize,
			sent: 0,
			data: data
		};

		uploadTo && (fileInfo.uploadTo = uploadTo);

		// check file size
		if (self.maxFileSize && self.maxFileSize > 0) {
			if (file.size > +self.maxFileSize) {
				return self.emit('error',
					new Error('Max Uploading File size must be under ' + self.maxFileSize + ' byte(s).'),
					{
						uploadId: fileInfo.id,
						name: fileInfo.name,
						size: fileInfo.size,
						uploadTo: uploadTo,
						data: data
					}
				);
			}
		}

		// check file mime type if exists
		if (self.accepts && self.accepts.length > 0) {
			var found = false;

			for (var i = 0; i < self.accepts.length; i++) {
				var accept = self.accepts[i];

				if (file.type === accept) {
					found = true;
					break;
				}
			}

			if (!found) {
				return self.emit('error',
					new Error('Not Acceptable file type ' + file.type + ' of ' + file.name + '. Type must be one of these: ' + self.accepts.join(', ')),
					{
						uploadId: fileInfo.id,
						name: fileInfo.name,
						size: fileInfo.size,
						type: file.type,
						uploadTo: uploadTo,
						data: data
					}
				);
			}
		}

		// put into uploadingFiles list
		self.uploadingFiles[uploadId] = fileInfo;

		// request the server to make a file
		self.emit('start', {
			uploadId: fileInfo.id,
			name: fileInfo.name,
			size: fileInfo.size,
			uploadTo: uploadTo,
			data: data
		});

		socket.emit('socket.io-file::createFile', fileInfo);

		// if receiving the resume response then set the start point to the end
		// of the file on the server
		socket.once('socket.io-file::resume::' + uploadId, function (info) {
			fileInfo.sent = info.wrote;
			self.emit('resume', fileInfo);
		});

		socket.once('socket.io-file::request::' + uploadId, sendChunk);
		socket.on('socket.io-file::complete::' + uploadId, function (info) {
			info.uploadId = fileInfo.id;
			info.data = fileInfo.data;

			socket.removeAllListeners('socket.io-file::abort::' + uploadId);
			socket.removeAllListeners('socket.io-file::error::' + uploadId);
			socket.removeAllListeners('socket.io-file::complete::' + uploadId);

			// remove from uploadingFiles list
			delete self.uploadingFiles[uploadId];

			self.emit('complete', info);
		});
		socket.on('socket.io-file::abort::' + uploadId, function (info) {
			fileInfo.aborted = true;
			self.emit('abort', {
				uploadId: fileInfo.id,
				name: fileInfo.name,
				size: fileInfo.size,
				sent: fileInfo.sent,
				wrote: info.wrote,
				uploadTo: uploadTo,
				data: data
			});
		});
		socket.on('socket.io-file::error::' + uploadId, function (err) {
			self.emit('error',
				new Error(err.message),
				{
					uploadId: fileInfo.id,
					name: fileInfo.name,
					size: fileInfo.size,
					uploadTo: uploadTo,
					data: data
				}
			);
		});

		// read file
		var fileReader = new FileReader();

		fileReader.onloadstart = function () {
			self.emit('loadstart');
		};

		fileReader.onprogress = function (progress) {
			self.emit('progress', {
				loaded: progress.loaded,
				total: progress.total
			});
		};

		function sendChunk() {

			if (fileInfo.aborted) {
				return;
			}

			if (fileInfo.sent >= file.size) {
				socket.emit('socket.io-file::done::' + uploadId);
				return;
			}

			var slice = file.slice(fileInfo.sent, fileInfo.sent + self.chunkSize);
			var chunk = fileReader.readAsArrayBuffer(slice);

			fileReader.onloadend = function () {

				var buffer = fileReader.result;

				self.emit('stream', {
					uploadId: fileInfo.id,
					name: fileInfo.name,
					size: fileInfo.size,
					sent: fileInfo.sent,
					uploadTo: uploadTo,
					data: data
				});

				fileInfo.sent += buffer.byteLength;
				self.uploadingFiles[uploadId] = fileInfo;

				socket.once('socket.io-file::request::' + uploadId, sendChunk);
				socket.emit('socket.io-file::stream::' + uploadId, buffer);

			}

		}


	}
21992
@Override
	public boolean upload(String path, File file) {
		Assert.notNull(file, "file to upload is null !");
		return upload(path, file.getName(), file);
	}
757496
public ResponseInfo syncPut(File file, String key, String token, UploadOptions options) {
        final UpToken decodedToken = UpToken.parse(token);
        ResponseInfo info = areInvalidArg(key, null, file, token, decodedToken);
        if (info != null) {
            return info;
        }
        return FormUploader.syncUpload(client, config, file, key, decodedToken, options);
    }
927311
def upload_file(f):
    
    with FilesOpener(f) as files:
        response = requests.post(
            'https://telegra.ph/upload',
            files=files
        ).json()

    if isinstance(response, list):
        error = response[0].get('error')
    else:
        error = response.get('error')

    if error:
        raise TelegraphException(error)

    return [i['src'] for i in response]
606796
public ResponseInfo syncPut(String file, String key, String token, UploadOptions options) {
        return syncPut(new File(file), key, token, options);
    }
250131
def handle_request_files_upload(request):
    
    # FILES is a dictionary in Django but Ajax Upload gives the uploaded file
    # an ID based on a random number, so it cannot be guessed here in the code.
    # Rather than editing Ajax Upload to pass the ID in the querystring,
    # note that each upload is a separate request so FILES should only
    # have one entry.
    # Thus, we can just grab the first (and only) value in the dict.
    is_raw = False
    upload = list(request.FILES.values())[0]
    filename = upload.name
    return upload, filename, is_raw
818657
def request(self, path, method='GET', params=None, data=None, files=None,
                headers=None, raw=False, allow_redirects=True, stream=False,
                timeout=None):
        
        if not headers:
            headers = {}

        if timeout is None:
            timeout = self.timeout

        # All requests must include oauth_token
        headers['Authorization'] = 'token %s' % self.access_token

        if path.startswith(('http://', 'https://')):
            url = path
        else:
            url = BASE_URL + path
        logger.debug('url: %s', url)

        response = self.session.request(
            method, url, params=params, data=data, files=files,
            headers=headers, allow_redirects=allow_redirects, stream=stream,
            timeout=self.timeout)
        logger.debug('response: %s', response)
        if raw:
            return response

        return _process_response(response)
15767
def send_file(self, file):
        
        if self.logger:
            self.logger.debug("[ioc.extra.tornado.RouterHandler] send file %s" % file)

        self.send_file_header(file)

        fp = open(file, 'rb')
        self.write(fp.read())

        fp.close()
414546
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post):
    
    filehash = sha1sum(filename)
    files = {'filedata': open(filename, 'rb')}

    payload = {
        'sha1': filehash,
        'filename': os.path.basename(filename),
        'token': token,
        'nonce': nonce,
    }

    return method("%s/sign/%s" % (baseurl, format_), files=files, data=payload, verify=cert)
684577
def upload_file(self, file):
        """"""

        url = self._get_url('/api/1.0/upload/post')

        fcontent = FileContent(file)
        binary_data = fcontent.get_binary()

        headers = self._get_request_headers()
        req = urllib.request.Request(url, binary_data, headers)
        req.add_header('Content-type', fcontent.get_content_type())
        req.add_header('Content-length', len(binary_data))
        resp = urllib.request.urlopen(req)   

        return definition.UploadPostResponse(_response_to_json(resp))
1020047
public void put(final File file, final String key, String token, final UpCompletionHandler complete,
                    final UploadOptions options) {
        final UpToken decodedToken = UpToken.parse(token);
        if (areInvalidArg(key, null, file, token, decodedToken, complete)) {
            return;
        }

        Zone z = config.zone;
        z.preQuery(token, new Zone.QueryHandler() {
            @Override
            public void onSuccess() {
                long size = file.length();
                if (size <= config.putThreshold) {
                    FormUploader.upload(client, config, file, key, decodedToken, complete, options);
                    return;
                }
                String recorderKey = config.keyGen.gen(key, file);
                final WarpHandler completionHandler = warpHandler(complete, file != null ? file.length() : 0);
                ResumeUploader uploader = new ResumeUploader(client, config, file, key,
                        decodedToken, completionHandler, options, recorderKey);

                AsyncRun.runInMain(uploader);
            }

            @Override
            public void onFailure(int reason) {
                final ResponseInfo info = ResponseInfo.isStatusCodeForBrokenNetwork(reason) ?
                        ResponseInfo.networkError(reason, decodedToken) :
                        ResponseInfo.invalidToken("invalid token");
                complete.complete(key, info, null);
            }
        });

    }
536333
def get(self, file):
        
        uri = "{api}/repos/{origin}/contents/{path}".format(
            api=self.github_api_url,
            origin=self.origin,
            path=file.path
        )
        params = {
            "ref": file.branch
        }
        data = self.request("GET", uri, params=params)
        # We update the file blob because it exists and we need it for update
        if data.status_code == 200:
            data = json.loads(data.content.decode("utf-8"))
            file.blob = data["sha"]
        elif data.status_code == 404:
            pass
        else:
            decoded_data = json.loads(data.content.decode("utf-8"))
            return self.ProxyError(
                data.status_code, (decoded_data, "message"),
                step="get", context={
                    "uri": uri,
                    "params": params
                }
            )
        return file
836654
def scan_file(self, this_file, this_filename):
        
        params = {
            'api_key': self.api_key,
            'filename': this_filename
        }
        try:
            files = {'file': (this_file.name, open(this_file.name, 'rb'), 'application/octet-stream')}
        except TypeError as e:
            return dict(error=e.message)

        try:
            response = requests.post(self.base + 'file/upload', files=files, data=params)
        except requests.RequestException as e:
            return dict(error=e.message)

        return _return_response_and_status_code(response)
1284140
def upload(self, file_path, description=None, async=False):
        
        url = "documents?async={a}".format(a=async)
        return self.core.upload(file_path, url, description)
528605
def upload(self, f):
        
        if hasattr(f, 'read'):
            needs_closing = False
        else:
            f = open(f, 'rb')
            needs_closing = True
        # The Puush server can't handle non-ASCII filenames.
        # The official Puush desktop app actually substitutes ? for
        # non-ISO-8859-1 characters, which helps some Unicode filenames,
        # but some are still let through and encounter server errors.
        # Try uploading a file named åäö.txt through the desktop app -
        # it won't work. It's better to let this Python API do that,
        # however, with the behavior probably intended in the desktop app.
        filename = os.path.basename(f.name).encode('ascii', 'replace')
        filename = filename.decode('ascii') # Requests doesn't like bytes
        md5 = md5_file(f)
        
        data = {
            'z': 'meaningless',
            'c': md5
        }
        files = {
            'f': (filename, f)
        }
        
        res = self._api_request('up', data=data, files=files)[0]
        if res[0] == '-1':
            raise PuushError("File upload failed.")
        elif res[0] == '-3':
            raise PuushError("File upload failed: hash didn't match with "
                "the file the server received.")
        
        if needs_closing:
            f.close()
        
        _, url, id, size = res
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return self._File(id, url, filename, now, 0)