fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return (content_type, body) ready for httplib.HTTP instance
9536
def encode_multipart_formdata(fields, files):
    
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('Content-Type: %s' % guess_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
1007201
def add_input_data(self, datastream, data_type, options, data):
        

        url = self.get_add_input_data_url(datastream, options)

        form_data = {
            'files': {
                'data': (
                    Utils.random_string(10)+('.json' if data_type == 'json' else '.csv'),
                    StringIO(data),
                    'text/plain;charset=UTF-8',
                    {'Expires': '0'}
                )
            }
        }
        response = self.http.fpost(url, form_data)
        return response
372324
def upload(self, url, filename, data=None, formname=None,
               otherfields=()):
        
        if data is None:
            data = open(filename, 'rb')
        self._upbuffer = StringIO.StringIO(get_upload_form(filename, data,
                                                           formname,
                                                           otherfields))
        ulheaders = self.stdheaders.copy()
        ulheaders['Content-Type'] = 'multipart/form-data; boundary=' + BND
        ulheaders['Content-Length'] = len(uploadforms[filename])
        self.ulsize = len(uploadforms[filename])
        webclient = self.dupe()
        webclient.request('POST', url, self._upbuffer, ulheaders)
        rsp = webclient.getresponse()
        # peer updates in progress should already have pointers,
        # subsequent transactions will cause memory to needlessly double,
        # but easiest way to keep memory relatively low
        try:
            del uploadforms[filename]
        except KeyError:  # something could have already deleted it
            pass
        self.rspstatus = rsp.status
        if rsp.status != 200:
            raise Exception('Unexpected response in file upload: ' +
                            rsp.read())
        return rsp.read()
676633
def encode_multipart(data, files):
    
    body = BytesIO()
    boundary = choose_boundary()
    part_boundary = b('--%s\r\n' % boundary)
    writer = codecs.lookup('utf-8')[3]

    if isinstance(data, dict):
        for name, values in data.items():
            if not isinstance(values, (list, tuple, set)):
                # behave like urllib.urlencode(dict, 1)
                values = (values, )
            for value in values:
                body.write(part_boundary)
                writer(body).write('Content-Disposition: form-data; '
                                   'name="%s"\r\n' % name)
                body.write(b'Content-Type: text/plain\r\n\r\n')
                if isinstance(value, int):
                    value = str(value)
                if py3k and isinstance(value, str):
                    writer(body).write(value)
                else:
                    body.write(value)
                body.write(b'\r\n')

    for fieldname, f in files.items():
        if isinstance(f, tuple):
            filename, f = f
        elif hasattr(f, 'name'):
            filename = basename(f.name)
        else:
            filename = None
            raise UrlfetchException("file must has filename")

        if hasattr(f, 'read'):
            value = f.read()
        elif isinstance(f, basestring):
            value = f
        else:
            value = str(f)

        body.write(part_boundary)
        if filename:
            writer(body).write('Content-Disposition: form-data; name="%s"; '
                               'filename="%s"\r\n' % (fieldname, filename))
            body.write(b'Content-Type: application/octet-stream\r\n\r\n')
        else:
            writer(body).write('Content-Disposition: form-data; name="%s"'
                               '\r\n' % name)
            body.write(b'Content-Type: text/plain\r\n\r\n')

        if py3k and isinstance(value, str):
            writer(body).write(value)
        else:
            body.write(value)
        body.write(b'\r\n')

    body.write(b('--' + boundary + '--\r\n'))

    content_type = 'multipart/form-data; boundary=%s' % boundary

    return content_type, body.getvalue()
1196212
def file_list(self, page_size: int, fields: str, order_by: str, query: str) -> dict:
        
        service = self.__get_service()
        results = service.files().list(
            pageSize=page_size,
            fields=fields,
            orderBy=order_by,
            q=query
        ).execute()
        return results.get('files', [])
279159
def fields(markdown)
      fields = []
      if markdown.file
        fields.push(title: 'file',
                    value: markdown.file,
                    short: true)
      end
      if markdown.line
        fields.push(title: 'line',
                    value: markdown.line,
                    short: true)
      end
      fields
    end
304219
function buildData(context) {

    if (/^Head|Get|Delete$/.test( context.method ))  return '';

    const request = context.request;

    if (request.type !== 'multipart/form-data')  return request.body;

    const form = new FormData();

    for (let key in request.fields)  form.append(key, request.fields[ key ]);

    for (let key in request.files)
        request.files[ key ].forEach(file =>
            form.append(key,  createReadStream( file.path ),  file.name)
        );

    return form;
}
806779
def file_field(method, options = {})
      bootstrap = form_bootstrap.scoped(options.delete(:bootstrap))
      return super if bootstrap.disabled

      draw_form_group(bootstrap, method, options) do
        if bootstrap.custom_control
          content_tag(:div, class: "custom-file") do
            add_css_class!(options, "custom-file-input")
            remove_css_class!(options, "form-control")
            label_text = options.delete(:placeholder)
            concat super(method, options)

            label_options = { class: "custom-file-label" }
            label_options[:for] = options[:id] if options[:id].present?
            concat label(method, label_text, label_options)
          end
        else
          super(method, options)
        end
      end
    end
153372
def get_post_fields(request):
    '''
    '''
    fields = dict()
    for field,value in request.form.items():
        fields[field] = value
    return fields
232712
def upload_files(files, options = {})
      data = upload_params(options).for_file_upload(files)

      response = @upload_connection.post('/base/', data)

      response.body.values.map! { |f| Uploadcare::Api::File.new(self, f) }
    end
571913
def parse_multipart_form(body, boundary):
    '''
    '''
    files = RequestParameters()
    fields = RequestParameters()

    form_parts = body.split(boundary)
    for form_part in form_parts[1:-1]:
        file_name = None
        file_type = None
        field_name = None
        line_index = 2
        line_end_index = 0
        while not line_end_index == -1:
            line_end_index = form_part.find(b'\r\n', line_index)
            form_line = form_part[line_index:line_end_index].decode('utf-8')
            line_index = line_end_index + 2

            if not form_line:
                break

            colon_index = form_line.index(':')
            form_header_field = form_line[0:colon_index].lower()
            form_header_value, form_parameters = parse_header(
                form_line[colon_index + 2:])

            if form_header_field == 'content-disposition':
                if 'filename' in form_parameters:
                    file_name = form_parameters['filename']
                field_name = form_parameters.get('name')
            elif form_header_field == 'content-type':
                file_type = form_header_value

        post_data = form_part[line_index:-4]
        if file_name or file_type:
            file = File(type=file_type, name=file_name, body=post_data)
            if field_name in files:
                files[field_name].append(file)
            else:
                files[field_name] = [file]
        else:
            value = post_data.decode('utf-8')
            if field_name in fields:
                fields[field_name].append(value)
            else:
                fields[field_name] = [value]

    return fields, files
265804
public function definition_after_data() {
        $mform = $this->_form;
        $cohortfile = $mform->getElementValue('cohortfile');
        $allowsubmitform = false;
        if ($cohortfile && ($file = $this->get_cohort_file($cohortfile))) {
            // File was uploaded. Parse it.
            $encoding = $mform->getElementValue('encoding')[0];
            $delimiter = $mform->getElementValue('delimiter')[0];
            $contextid = $mform->getElementValue('contextid')[0];
            if (!empty($contextid) && ($context = context::instance_by_id($contextid, IGNORE_MISSING))) {
                $this->processeddata = $this->process_upload_file($file, $encoding, $delimiter, $context);
                if ($this->processeddata && count($this->processeddata) > 1 && !$this->processeddata[0]['errors']) {
                    $allowsubmitform = true;
                }
            }
        }
        if (!$allowsubmitform) {
            // Hide submit button.
            $el = $mform->getElement('buttonar')->getElements()[0];
            $el->setValue('');
            $el->freeze();
        } else {
            $mform->setExpanded('cohortfileuploadform', false);
        }

    }
1121918
def get_file_fields():
    

    # get models

    all_models = apps.get_models()

    # get fields

    fields = []

    for model in all_models:
        for field in model._meta.get_fields():
            if isinstance(field, models.FileField):
                fields.append(field)

    return fields
655618
def _init_data(self, data, obj, files):
        
        data = self.prepare(data)

        # Initialize sub-forms
        for name, subform in self._forms.items():
            obj_value = get_obj_value(obj, name)
            if inspect.isclass(subform):
                fclass = subform
            else:
                fclass = subform.__class__
            subform_prefix = '{prefix}{name}.'.format(
                prefix=self._prefix,
                name=name.lower()
            )
            subform = fclass(
                data,
                obj_value,
                files=files,
                locale=self._locale,
                tz=self._tz,
                prefix=subform_prefix,
                backref=getattr(subform, '_backref', None)
            )

            self._forms[name] = subform
            setattr(self, name, subform)
            self._input_data = self._input_data or subform._input_data

        # Initialize form-sets
        for name, formset in self._sets.items():
            sclass = formset.__class__
            objs = formset._objs or get_obj_value(obj, name)
            formset_name = '{prefix}{name}'.format(
                prefix=self._prefix,
                name=name.lower()
            )
            formset = sclass(
                form_class=formset._form_class,
                name=formset_name,
                data=data,
                objs=objs,
                files=files,
                locale=self._locale,
                tz=self._tz,
                create_new=formset._create_new,
                backref=formset._backref
            )
            self._sets[name] = formset
            setattr(self, name, formset)
            for _form in formset._forms:
                self._input_data = self._input_data or _form._input_data

        # Initialize fields
        for name, field in self._fields.items():
            subdata = data.getlist(self._prefix + name)
            subfiles = files.getlist(self._prefix + name)
            self._input_data = self._input_data or subdata or subfiles
            obj_value = get_obj_value(obj, name)
            was_deleted = self._prefix + name + '__deleted' in data
            if was_deleted:
                subdata = obj_value = subfiles = None
            field.load_data(subdata, obj_value, file_data=subfiles,
                            locale=self._locale, tz=self._tz)
            # delete field data
            if was_deleted:
                field._deleted = True
1254891
def get_fields(model, fields, meta=None):
    
    model = get_model(model)
    if fields is not None:
        f = fields
    elif meta and hasattr(model, meta):
        m = getattr(model, meta)
        if hasattr(m, 'fields'):
            f = m.fields
        else:
            f = model._fields_list
    else:
        f = model._fields_list
        
    fields_list = []
    for x in f:
        field = {}
        if isinstance(x, str):  #so x is field_name
            field['name'] = x
        elif isinstance(x, tuple):
            field['name'] = x[0]
            field['field'] = x[1]
        elif isinstance(x, dict):
            field = x.copy()
        else:
            raise UliwebError('Field definition {!r} is not right, it should be just like (field_name, form_field_obj)'.format(x))
        
        if 'prop' not in field:
            if hasattr(model, field['name']):
                field['prop'] = getattr(model, field['name'])
            else:
                field['prop'] = None
        
        fields_list.append((field['name'], field))
    return fields_list
1341491
@POST
  @Path("/upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail) {

    Config config = createConfig();

    if (uploadedInputStream == null) {
      String msg = "input stream is null";
      LOG.error(msg);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(msg)).build();
    }
    if (fileDetail == null) {
      String msg = "form data content disposition is null";
      LOG.error(msg);
      return Response.status(Response.Status.BAD_REQUEST)
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(msg)).build();
    }

    String uploadDir = config.getStringValue(FILE_SYSTEM_DIRECTORY);

    final String fileName = UUID.randomUUID() + "-" + fileDetail.getFileName();

    final String uploadedFileLocation
        = uploadDir + "/" + fileName;

    // save it
    try {
      FileHelper.writeToFile(uploadedInputStream, uploadedFileLocation);
    } catch (IOException e) {
      LOG.error("error uploading file {}", fileDetail.getFileName(), e);
      return Response.serverError()
          .type(MediaType.APPLICATION_JSON)
          .entity(Utils.createMessage(e.getMessage()))
          .build();
    }

    String uri = String.format("http://%s:%s/api/v1/file/download/%s",
        getHostNameOrIP(), getPort(), fileName);

    return Response.status(Response.Status.OK).entity(uri).build();
  }
687759
def _get_fields(self):
        
        if self.data is not None:
            return self.begin, self.end, self.data
        else:
            return self.begin, self.end