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
770531
def __encodeMultipart(self, fields, files):
        
        boundary = mimetools.choose_boundary()
        crlf = '\r\n'

        l = []
        for k, v in fields:
            l.append('--' + boundary)
            l.append('Content-Disposition: form-data; name="%s"' % k)
            l.append('')
            l.append(v)
        for (k, f, v) in files:
            l.append('--' + boundary)
            l.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (k, f))
            l.append('Content-Type: %s' % self.__getContentType(f))
            l.append('')
            l.append(v)
        l.append('--' + boundary + '--')
        l.append('')
        body = crlf.join(l)

        return boundary, body
543037
def prepare_body(self, data, files):
        """"""

        # Check if file, fo, generator, iterator.
        # If not, run through normal process.

        # Nottin' on you.
        body = None
        content_type = None
        length = None

        is_stream = all([
            hasattr(data, '__iter__'),
            not isinstance(data, (basestring, list, tuple, dict))
        ])

        try:
            length = super_len(data)
        except (TypeError, AttributeError, UnsupportedOperation):
            length = None

        if is_stream:
            body = data

            if files:
                raise NotImplementedError('Streamed bodies and files are mutually exclusive.')

            if length is not None:
                self.headers['Content-Length'] = builtin_str(length)
            else:
                self.headers['Transfer-Encoding'] = 'chunked'
        else:
            # Multi-part file uploads.
            if files:
                (body, content_type) = self._encode_files(files, data)
            else:
                if data:
                    body = self._encode_params(data)
                    if isinstance(data, basestring) or hasattr(data, 'read'):
                        content_type = None
                    else:
                        content_type = 'application/x-www-form-urlencoded'

            self.prepare_content_length(body)

            # Add content-type if it wasn't explicitly provided.
            if (content_type) and (not 'content-type' in self.headers):
                self.headers['Content-Type'] = content_type

        self.body = body
139905
def content_type(path, filename)
      type = (filename.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
      case type
      when %r"jp(e|g|eg)"            then "image/jpeg"
      when %r"tiff?"                 then "image/tiff"
      when %r"png", "gif", "bmp"     then "image/#{type}"
      when "txt"                     then "text/plain"
      when %r"html?"                 then "text/html"
      when "js"                      then "application/js"
      when "csv", "xml", "css"       then "text/#{type}"
      else
        # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
        content_type = (`file -b --mime-type #{path}`.split(':').last.strip rescue "application/x-#{type}")
        content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/)
        content_type
      end
    end
1001993
def __body_format(self, body):
        

        ctype, pdict = parse_header(self.content_type)
        if ctype == 'application/json':
            self.form = json.loads(body.decode())

        elif ctype == 'application/x-www-form-urlencoded':
            for key, value in parse_qs(body).items():
                    self.form[key.decode()] = [one_value.decode() for one_value in value]

        elif ctype == "multipart/form-data":
            safe_env = {
                'QUERY_STRING': '',
                'REQUEST_METHOD': self.method.upper(),
                'CONTENT_TYPE': self.content_type,
                'CONTENT_LENGTH': self.headers.get('Content-Length', '-1')
            }
            fields = FieldStorage(io.BytesIO(body), environ=safe_env, keep_blank_values=True)

            fields = fields.list or []
            for field in fields:
                if field.filename:
                    self.form[field.name] = File(field.filename, field.file)
                else:
                    self.form[field.name] = field.value
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
613769
def POST(self):
        
        post = FormsDict()
        # We default to application/x-www-form-urlencoded for everything that
        # is not multipart and take the fast path (also: 3.1 workaround)
        if not self.content_type.startswith('multipart/'):
            maxlen = max(0, min(self.content_length, self.MEMFILE_MAX))
            pairs = _parse_qsl(tonat(self.body.read(maxlen), 'latin1'))
            for key, value in pairs[:self.MAX_PARAMS]:
                post[key] = value
            return post

        safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
        for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
            if key in self.environ: safe_env[key] = self.environ[key]
        args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)
        if py >= (3,2,0):
            args['encoding'] = 'ISO-8859-1'
        if NCTextIOWrapper:
            args['fp'] = NCTextIOWrapper(args['fp'], encoding='ISO-8859-1',
                                         newline='\n')
        data = cgi.FieldStorage(**args)
        for item in (data.list or [])[:self.MAX_PARAMS]:
            post[item.name] = item if item.filename else item.value
        return post
672800
def encode_multipart_formdata(self, fields, filename, verbose=False):
        
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        if verbose is True:
            print(('Encoding ' + filename + ' for upload...'))
        fin = open(filename, 'rb')
        fout = open(filename + '.b64', 'wb')
        fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8'))
        fout.write(bytearray('Content-Disposition: form-data'
                             '; name="file"; filename="' +
                             filename + '"' + CRLF, "utf-8"))
        fout.write(bytearray('Content-Type: application/octet-stream' + CRLF,
                             'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        shutil.copyfileobj(fin, fout)
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.close()
        fin.close()
        return content_type
547906
private String getFileName(Field field) {
        String fileName = field.getAnnotation(Plugin.Data.class).value();
        if ("##default".equals(fileName)) {
            fileName = getName() + ".json";
        }
        return fileName;
    }
639986
def schema_keys
      schema_file = File.join(Rails.root, 'solr_conf', 'schema.xml')
      file = File.open(schema_file)
      doc = Nokogiri::XML(file)
      file.close
      doc.xpath('//fields/field').map { |f| f.attr('name') }
    end
226119
function File (schema) {
  /**
   * The {@link Schema} that this file belongs to.
   *
   * @type {Schema}
   */
  this.schema = schema;

  /**
   * The file's full (absolute) URL, without any hash
   *
   * @type {string}
   */
  this.url = '';

  /**
   * The file's data. This can be any data type, including a string, object, array, binary, etc.
   *
   * @type {*}
   */
  this.data = undefined;

  /**
   * The file's MIME type (e.g. "application/json", "text/html", etc.), if known.
   *
   * @type {?string}
   */
  this.mimeType = undefined;

  /**
   * The file's encoding (e.g. "utf-8", "iso-8859-2", "windows-1251", etc.), if known
   *
   * @type {?string}
   */
  this.encoding = undefined;

  /**
   * Internal stuff. Use at your own risk!
   *
   * @private
   */
  this[__internal] = {
    /**
     * Keeps track of the state of each file as the schema is being read.
     *
     * @type {number}
     */
    state: 0,
  };
}
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
800382
public function saveFiles()
    {
        $fileFields = $this->getFileFields();

        foreach ($fileFields as $fieldName => $options) {
            $file = Request::file($fieldName);
            if ($file instanceof UploadedFile && $file->isValid()) {
                $filename = $file->getClientOriginalName();
                $fileSavePath = $this->getFileSavePath($options['dirName']);

                $file->move($fileSavePath, $filename);

                $this->attributes[$fieldName] = $fileSavePath.$filename;
            }
        }
    }
71281
def encode_multipart_formdata(self, fields, files, baseName, verbose=False):
        
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        if verbose is True:
            print(('Encoding ' + baseName + ' for upload...'))
        fin = self._open(files, 'rb')
        fout = self._open(files + '.b64', 'wb')
        fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8'))
        fout.write(bytearray('Content-Disposition: form-data'
                             '; name="file"; filename="' + baseName + '"' + CRLF, "utf-8"))
        fout.write(bytearray('Content-Type: application/octet-stream' + CRLF,
                             'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        shutil.copyfileobj(fin, fout)
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.close()
        fin.close()
        return content_type
416290
function getFields() {
                return storage.headObject({
                  Bucket: bucket,
                  Key: storageObject.Key
                })
                  .then(function(storageObjectHead) {

                    return {
                      name: path.parse(storageObject.Key).name,
                      location: storageObject.Key,
                      size: storageObjectHead.ContentLength,
                      contentType: storageObjectHead.ContentType,
                      type: services.helpers.mediaType(storageObjectHead.ContentType)
                    };
                  });
              }
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);
        }

    }
17682
public void setupFields()
    {
        FieldInfo field = null;
        field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Integer.class);
        field.setHidden(true);
        field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Date.class);
        field.setHidden(true);
        field = new FieldInfo(this, DELETED, 10, null, new Boolean(false));
        field.setDataClass(Boolean.class);
        field.setHidden(true);
        field = new FieldInfo(this, DESCRIPTION, 60, null, null);
        field = new FieldInfo(this, SEQUENCE, 10, null, null);
        field.setDataClass(Integer.class);
        field = new FieldInfo(this, KIND, 10, null, null);
        field = new FieldInfo(this, PART_TYPE, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field = new FieldInfo(this, JNLP_FILE_ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
        field.setDataClass(Integer.class);
        field = new FieldInfo(this, PATH, 128, null, null);
    }
1299608
def formdata_post(url, fields):
    
    content_type, data = formdata_encode(fields)
    req = urllib2.Request(url, data)
    req.add_header('Content-Type', content_type)
    return urllib2.urlopen(req).read()