Builds form parameters.

        :param post_params: Normal form parameters.
        :param files: File parameters.
        :return: Form parameters with files.
167244
def prepare_post_parameters(self, post_params=None, files=None):
        
        params = []

        if post_params:
            params = post_params

        if files:
            for k, v in six.iteritems(files):
                if not v:
                    continue
                file_names = v if type(v) is list else [v]
                for n in file_names:
                    with open(n, 'rb') as f:
                        filename = os.path.basename(f.name)
                        filedata = f.read()
                        mimetype = (mimetypes.guess_type(filename)[0] or
                                    'application/octet-stream')
                        params.append(
                            tuple([k, tuple([filename, filedata, mimetype])]))

        return params
285109
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
        MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
        for (Entry<String, Object> param : formParams.entrySet()) {
            if (param.getValue() instanceof File) {
                File file = (File) param.getValue();
                Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
                MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
                mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
            } else {
                Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
                mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
            }
        }
        return mpBuilder.build();
    }
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
791343
def process(parsed_files, opts)
      r = aggregate(parsed_files)
      r = pre_process(r, opts)
      r = to_class_objects(r, opts)
      return post_process(r, opts)
    end
23984
def api_post_multipart(self, action, data, binary_data_param):
        
        binary_data = {}
        data = data.copy()

        try:
            file_handles = []
            for param in binary_data_param:
                if param in data:
                    binary_data[param] = file_handle = open(data[param], 'r')
                    file_handles.append(file_handle)
                    del data[param]
            json_payload = self._prepare_json_payload(data)

            return self._http_request(action, json_payload, "POST", binary_data)
        finally:
            for file_handle in file_handles:
                file_handle.close()
619837
def get_post_file(self, hdr, f_in, clen, post, files):
        """"""
        lens = {
            'clen': clen,
            'push': [],
        }
        prefix = "boundary="
        if not hdr.startswith(prefix):
            return None
        boundary = hdr[len(prefix):].strip().encode('utf8')
        if not boundary:
            return None
        boundary = b'--' + boundary
        raw_boundary = b'\r\n' + boundary
        end_boundary = boundary + b'--'

        def push_back(line):
            ln = BytesIO()
            ln.write(line)
            ln.flush()
            ln.seek(0)
            lens['clen'] += len(line)
            lens['push'].append(ln)

        def read_line():
            line = b''
            while not line.endswith(b'\n') and lens['push']:
                br = lens['push'].pop()
                line += br.readline()
                tmp = br.read(1)
                if tmp != b'':
                    br.seek(br.tell() - 1)
                    lens['push'].append(br)
            if not line.endswith(b'\n'):
                line += f_in.readline(lens['clen'])
            lens['clen'] -= len(line)
            if line == b'' or lens['clen'] < 0:
                raise ValueError("Unexpected EOF")
            return line.strip()

        def read(length):
            res = b''
            while len(res) < length and lens['push']:
                br = lens['push'].pop()
                res += br.read(length - len(res))
                tmp = br.read(1)
                if tmp != b'':
                    br.seek(br.tell() - 1)
                    lens['push'].append(br)
            if len(res) < length:
                res += f_in.read(length - len(res))
            lens['clen'] -= len(res)
            if res == b'' or lens['clen'] < 0:
                raise ValueError("Unexpected EOF")
            return res

        def parse_file():
            f = BytesIO()
            buff_size = 10 * 1024

            def write_buff(buff):
                if f.tell() + len(buff) > self.server.max_file_size:
                    raise PreventDefaultResponse(
                        413, "Uploaded file is too large! {0} > {1}".format(
                            f.tell() + len(buff), self.server.max_file_size))
                f.write(buff)
                f.flush()

            buff = b""
            while True:
                buff += read(min(lens['clen'], buff_size))
                bix = buff.find(raw_boundary)
                if bix >= 0:
                    write_buff(buff[:bix])
                    push_back(buff[bix + len(raw_boundary) - len(boundary):])
                    break
                out_split = max(len(buff) - len(raw_boundary), 0)
                if out_split > 0:
                    write_buff(buff[:out_split])
                    buff = buff[out_split:]
            f.seek(0)
            return f

        def parse_field():
            return parse_file().read().decode('utf8')

        while True:
            line = read_line()
            if line == end_boundary:
                if lens['clen'] > 0:
                    raise ValueError(
                        "Expected EOF got: {0}".format(
                            repr(f_in.read(lens['clen']))))
                return
            if line != boundary:
                raise ValueError(
                    "Expected boundary got: {0}".format(repr(line)))
            headers = {}
            while True:
                line = read_line()
                if not line:
                    break
                key, value = line.split(b':', 1)
                headers[key.lower()] = value.strip()
            name = None
            if b'content-disposition' in headers:
                cdis = headers[b'content-disposition']
                if not cdis.startswith(b'form-data'):
                    raise ValueError(
                        "Unknown content-disposition: {0}".format(repr(cdis)))
                name_field = b'name="'
                ix = cdis.find(name_field)
                if ix >= 0:
                    name = cdis[ix + len(name_field):]
                    name = name[:name.index(b'"')].decode('utf8')
            ctype = None
            if b'content-type' in headers:
                ctype = headers[b'content-type']
            # b'application/octet-stream': # we treat all files the same
            if ctype is not None:
                files[name] = parse_file()
            else:
                post[name] = parse_field()
858441
def _post(self, url, data=None, **kwargs):
        

        # Remove non-ASCII characters from filenames due to a limitation of the combination of
        # urllib3 (via python-requests) and our server
        # https://github.com/requests/requests/issues/2117
        # Internal Ticket #3090
        if "files" in kwargs and kwargs["files"] is not None:
            acceptable_chars = "0123456789" + "abcdefghijklmnopqrstuvwxyz" + \
                               "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + " _-.,()[]{}"
            for param_name, fp in kwargs["files"].items():
                if isinstance(fp, (tuple, list)):
                    filename, fp = fp
                else:
                    filename = requests.utils.guess_filename(fp) or param_name

                def encode(char):
                    try:
                        if char in acceptable_chars:
                            return char
                    except UnicodeDecodeError:
                        pass
                    return "x{:02x}".format(ord(char))
                filename = "".join(encode(x) for x in filename)

                kwargs["files"][param_name] = (filename, fp)

        for i in itertools.count(1):
            try:
                return self.session.post(url, data=data, timeout=self.timeout, **kwargs)
            except requests.exceptions.Timeout as e:
                # exhausted all retries
                if i >= self.retries:
                    raise ConnectionError(e)
            except requests.exceptions.RequestException as e:
                raise ConnectionError(e)

            # exponential backoff
            max_backoff = 4 ** i / 10   # .4, 1.6, 6.4, 25.6, ...
            time.sleep(random.uniform(0, max_backoff))
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
938018
public void setFormParams(TreeSet<HtmlParameter> postParams) {
		if (postParams.isEmpty()) {
			this.setBody("");
			return;
		}
		
		StringBuilder postData = new StringBuilder();
		
		for(HtmlParameter parameter: postParams) {
			if (parameter.getType() != HtmlParameter.Type.form) {
				continue;
			}
			
			postData.append(parameter.getName());
			postData.append('=');
			postData.append(parameter.getValue());
			postData.append('&');
		}
		
		String data = "";
		if (postData.length() != 0) {
			data = postData.substring(0, postData.length() - 1);
		}
		
		this.setBody(data);
	}
763613
def files(self):
        
        files = MultiDict()
        for name, item in self.POST.iterallitems():
            if hasattr(item, 'filename'):
                files[name] = item
        return files
367154
def files(self):
        
        files = FormsDict()
        for name, item in self.POST.allitems():
            if isinstance(item, FileUpload):
                files[name] = item
        return files
757919
def handle_register_or_upload(post_data, files, user, repository):
    
    name = post_data.get('name')
    version = post_data.get('version')

    if settings.LOCALSHOP_VERSIONING_TYPE:
        scheme = get_versio_versioning_scheme(settings.LOCALSHOP_VERSIONING_TYPE)
        try:
            Version(version, scheme=scheme)
        except AttributeError:
            response = HttpResponseBadRequest(
                reason="Invalid version supplied '{!s}' for '{!s}' scheme.".format(
                    version, settings.LOCALSHOP_VERSIONING_TYPE))
            return response

    if not name or not version:
        logger.info("Missing name or version for package")
        return HttpResponseBadRequest('No name or version given')

    try:
        condition = Q()
        for search_name in get_search_names(name):
            condition |= Q(name__iexact=search_name)

        package = repository.packages.get(condition)

        # Error out when we try to override a mirror'ed package for now
        # not sure what the best thing is
        if not package.is_local:
            return HttpResponseBadRequest(
                '%s is a pypi package!' % package.name)

        try:
            release = package.releases.get(version=version)
        except ObjectDoesNotExist:
            release = None
    except ObjectDoesNotExist:
        package = None
        release = None

    # Validate the data
    form = forms.ReleaseForm(post_data, instance=release)
    if not form.is_valid():
        return HttpResponseBadRequest(reason=form.errors.values()[0][0])

    if not package:
        pkg_form = forms.PackageForm(post_data, repository=repository)
        if not pkg_form.is_valid():
            return HttpResponseBadRequest(
                reason=six.next(six.itervalues(pkg_form.errors))[0])
        package = pkg_form.save()

    release = form.save(commit=False)
    release.package = package
    release.save()

    # If this is an upload action then process the uploaded file
    if files:
        files = {
            'distribution': files['content']
        }
        filename = files['distribution']._name
        try:
            release_file = release.files.get(filename=filename)
            if settings.LOCALSHOP_RELEASE_OVERWRITE is False:
                message = 'That it already released, please bump version.'
                return HttpResponseBadRequest(message)
        except ObjectDoesNotExist:
            release_file = models.ReleaseFile(
                release=release, filename=filename)

        form_file = forms.ReleaseFileForm(
            post_data, files, instance=release_file)
        if not form_file.is_valid():
            return HttpResponseBadRequest('ERRORS %s' % form_file.errors)
        release_file = form_file.save(commit=False)
        release_file.save()

    return HttpResponse()
408980
def _post(self, url, data={}, **kwargs):
        """"""
        if 'files' in kwargs:
            req = self._session.post(self._api_prefix + url, auth=self._session.auth, data=data, **kwargs)
            return self._action(req)

        req = self._session.post(self._api_prefix + url, data=data, **kwargs)
        return self._action(req)
1313382
public HttpRequest form(String name, File... files) {
		if (1 == files.length) {
			final File file = files[0];
			return form(name, file, file.getName());
		}
		return form(name, new MultiFileResource(files));
	}
1288666
protected function setPostParameters()
    {
        $this->curlOptions[ 'POST' ] = true;

        $parameters = $this->packageOptions[ 'data' ];
        if( !empty($this->packageOptions[ 'files' ]) ) {
            foreach( $this->packageOptions[ 'files' ] as $key => $file ) {
                $parameters[ $key ] = $this->getCurlFileValue( $file[ 'fileName' ], $file[ 'mimeType' ], $file[ 'postFileName'] );
            }
        }

        if( $this->packageOptions[ 'asJsonRequest' ] ) {
            $parameters = json_encode($parameters);
        }

        $this->curlOptions[ 'POSTFIELDS' ] = $parameters;
    }
954038
def gen_post_map(file_name, ext_url=''):
    '''
    
    '''
    with open(file_name, 'a') as fout:
        for kind_key in router_post:
            recent_posts = MPost.query_all(kind=kind_key, limit=1000000)
            for recent_post in recent_posts:
                url = os.path.join(SITE_CFG['site_url'],
                                   router_post[recent_post.kind],
                                   ext_url,
                                   recent_post.uid)
                fout.write('{url}\n'.format(url=url))
713053
def fetch(*args, **kwargs):
    
    data = kwargs.get('data', None)
    files = kwargs.get('files', {})

    if data and isinstance(data, (basestring, dict)) or files:
        return post(*args, **kwargs)
    return get(*args, **kwargs)