Send file

        https://core.telegram.org/bots/api#inputfile

        :param file_type: field name
        :param method: API method
        :param file: String or io.IOBase
        :param payload: request payload
        :return: response
322892
async def send_file(self, file_type, method, file, payload) -> Union[Dict, base.Boolean]:
        
        if file is None:
            files = {}
        elif isinstance(file, str):
            # You can use file ID or URL in the most of requests
            payload[file_type] = file
            files = None
        else:
            files = {file_type: file}

        return await self.request(method, payload, files)
22826
def file_add_types(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/addTypes' % object_id, input_params, always_retry=always_retry, **kwargs)
1125121
def upload(self, file_obj):
        
        return self._client.upload_object(
            self._instance, self._bucket, self.name, file_obj)
1209485
def show
      response.headers['Content-Length'] = @attachment.file.size.to_s
      send_file(
        @attachment.file.path,
        {
          filename: @attachment.file_name,
          type: @attachment.file_mime_type,
          disposition: 'inline'
        }
      )
    end
641522
def from_file(self, filename):
        

        mimetype = mimetypes.guess_type(filename)[0] or "application/octal-stream"
        headers = {
            "Content-Type": mimetype,
            "Content-Length": str(os.path.getsize(filename)),
        }

        # upload file
        file_data = self._pump.request(
            "/api/user/{0}/uploads".format(self._pump.client.nickname),
            method="POST",
            data=open(filename, "rb").read(),
            headers=headers,
        )

        # now post it to the feed
        data = {
            "verb": "post",
            "object": file_data,
        }
        data.update(self.serialize())

        if not self.content and not self.display_name and not self.license:
            self._post_activity(data)
        else:
            self._post_activity(data, unserialize=False)

            # update post with display_name and content
            if self.content:
                file_data['content'] = self.content
            if self.display_name:
                file_data['displayName'] = self.display_name
            if self.license:
                file_data['license'] = self.license
            data = {
                "verb": "update",
                "object": file_data,
            }
            self._post_activity(data)

        return self
389434
def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None):
        
        self.logger.info('send photo %s', photo)
        payload = dict(chat_id=chat_id,
                       caption=caption,
                       reply_to_message_id=reply_to_message_id,
                       reply_markup=reply_markup)
        files = dict(photo=open(photo, 'rb'))
        return Message.from_api(self, **self._post('sendPhoto', payload, files))
640988
def post_file(api_method, file, parameters = {})
      parameters.merge!({"token" => @token})

      body = {}
      body.merge!({:method => api_method})
      body.merge!({:params => parameters})

      # Brightcove requires that the JSON-RPC call absolutely
      # be the first part of a multi-part POST like create_video.
      if RUBY_VERSION >= '1.9'
        payload = {}
      else
        payload = OrderedHash.new
      end

      payload[:json] = body.to_json
      payload[:file] = File.new(file, 'rb')

      execution_payload = {
        :method => :post,
        :url => @write_api_url,
        :payload => payload,
        :content_type => :json,
        :accept => :json,
        :multipart => true
      }

      execution_payload[:timeout] = @timeout if @timeout
      execution_payload[:open_timeout] = @open_timeout if @open_timeout

      response = RestClient::Request.execute(execution_payload)

      JSON.parse(response)
    end
1301762
def file_upload(f):
    

    @wraps(f)
    def file_upload_decorator(*args, **kwargs):
        # If the data is already transformed, we do not transform it any
        # further.
        task_data = _get_data_from_args(args)

        if task_data is None:
            logging.error("Task data is empty during FilesUploadDecorator.")

        task_data.transform_payload(lambda _: request.files.getlist('file'))
        return f(*args, **kwargs)

    return file_upload_decorator
128691
def upload_file(self, file_name, file_path):
        
        upload_key = Key(bucket=self.bucket, name=file_name)
        content_type = "text/plain"
        if file_name.endswith(".html"):
            content_type = "text/html"
        elif file_name.endswith(".jpg"):
            content_type = "image/jpeg"
        elif file_name.endswith(".png"):
            content_type = "image/png"
        upload_key.set_contents_from_filename(
            file_path,
            headers={"Content-Type": content_type})
        upload_key.url = \
            upload_key.generate_url(expires_in=3600).split("?")[0]
        try:
            upload_key.make_public()
        except Exception:
            pass
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)
183835
def send_file(service, file, fileName=None, password=None, ignoreVersion=False):

    if checkServerVersion(service, ignoreVersion=ignoreVersion) == False:
        print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m')

    ''' '''
    fileName = fileName if fileName != None else os.path.basename(file.name)

    print('Encrypting data from "' + fileName + '"')
    keys = secretKeys()
    encData = encrypt_file(file, keys)
    encMeta = encrypt_metadata(keys, fileName)

    print('Uploading "' + fileName + '"')
    secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys)

    if password != None:
        print('Setting password')
        sendclient.password.set_password(secretUrl, owner_token, password)

    return secretUrl, fileId, owner_token
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()
685203
def reply(self,message,message_type):
        
        if message_type == MULTIPART:
            raise Exception("Unsupported reply type")
            
        super(Replier,self).send(message,message_type)
329190
def upload(cls, path, document_type, is_protocol, description=""):
        
        file_name = os.path.basename(path)
        mime_type = mimetypes.guess_type(file_name)[0]
        data = base64.b64encode(open(path, 'rb').read())
        temp_uri = str(data, "utf-8")
        #href = "data:{mime_type};base64,{temp_uri}".format(mime_type=mime_type, temp_uri=temp_uri) 
        payload = {}
        payload["content_type"] = mime_type 
        payload["data"] = temp_uri
        payload["description"] = description
        payload["document_type_id"] = DocumentType(document_type).id
        payload["name"] =  file_name
        payload["is_protocol"] = is_protocol
        cls.post(payload)
197316
def upload_file_handle(
            self,
            bucket: str,
            key: str,
            src_file_handle: typing.BinaryIO,
            content_type: str=None,
            metadata: dict=None):
        
        raise NotImplementedError()
688568
function sendFile(params) {
    const p = params;
    
    checkParams(params);
    
    fs.lstat(p.name, (error, stat) => {
        if (error)
            return sendError(error, params);
        
        const isGzip = isGZIP(p.request) && p.gzip;
        const time = stat.mtime.toUTCString();
        const length = stat.size;
        const range = getRange(p.request, length);
        
        if (range)
            assign(p, {
                range,
                status: RANGE
            });
        
        assign(p, {
            time
        });
        
        if (!isGzip)
            p.length = length;
        
        setHeader(params);
        
        const options = {
            gzip    : isGzip,
            range,
        };
        
        files.pipe(p.name, p.response, options).catch((error) => {
            sendError(error, params);
        });
    });
}
643803
def send_file(from, message, file)
      if from.length > 20
        raise UsernameTooLong, "Username #{from} is `#{from.length} characters long. Limit is 20'"
      end

      response = self.class.post(@api.send_file_config[:url],
        :query => { :auth_token => @token },
        :body  => file_body(
          {
            :room_id        => room_id,
            :from           => from,
            :message        => message,
          }.send(@api.send_config[:body_format]), file
        ),
        :headers => file_body_headers(@api.headers)
      )

      ErrorHandler.response_code_to_exception_for :room, room_id, response
      true
    end