Pack an image from file into multipart-formdata post body
765262
def pack_image(filename, max_size, form_field='image'):
        """"""
        try:
            if os.path.getsize(filename) > (max_size * 1024):
                raise IdeaScalyError('File is too big, must be less than %skb.' % max_size)
        except os.error as e:
            raise IdeaScalyError('Unable to access file: %s' % e.strerror)

        # build the mulitpart-formdata body
        fp = open(filename, 'rb')

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise IdeaScalyError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise IdeaScalyError('Invalid file type for image: %s' % file_type)

        if isinstance(filename, six.text_type):
            filename = filename.encode('utf-8')

        BOUNDARY = b'Id34Sc4ly'
        body = list()
        body.append(b'--' + BOUNDARY)
        body.append('content-disposition: form-data; name="{0}";'
                    ' filename="{1}"'.format(form_field, filename)
                    .encode('utf-8'))
        body.append('content-type: {0}'.format(file_type).encode('utf-8'))
        body.append(b'')
        body.append(fp.read())
        body.append(b'--' + BOUNDARY + b'--')
        body.append(b'')
        fp.close()
        body = b'\r\n'.join(body)
        body_length = str(len(body))

        # build headers
        headers = {
            'content-type': 'multipart/form-data; boundary={0}'.format(BOUNDARY),
            'content-length': body_length
        }

        return headers, body
734290
function convertInlinePNG(source, dest) {
    if (!/^data\:image\/png/.test(source)) return Promise.reject(new Error('Source is not a PNG data-uri'));

    var base64data = source.split('data:image/png;base64,')[1];
    var buf = new Buffer(base64data, 'base64');

    return fs.writeFile(dest, buf)
    .then(function() {
        if (fs.existsSync(dest)) return;

        throw new Error('Error converting '+source+' into '+dest);
    });
}
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
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;
}
617341
def image_to_file(self, path, get_image=True):
        """"""
        if not self.image_url or get_image:
            if not self.refresh_image():
                return False

        response = requests.get(self.image_url, stream=True)

        if response.status_code != 200:
            _LOGGER.warning(
                "Unexpected response code %s when requesting image: %s",
                str(response.status_code), response.text)
            raise AbodeException((ERROR.CAM_IMAGE_REQUEST_INVALID))

        with open(path, 'wb') as imgfile:
            copyfileobj(response.raw, imgfile)

        return True
593236
def _prepare_files(self, encoding):
        
        content_type = 'multipart/form-data'
        if self.__op.consumes and content_type not in self.__op.consumes:
            raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes))

        boundary = uuid4().hex
        content_type += '; boundary={0}'
        content_type = content_type.format(boundary)

        # init stream
        body = io.BytesIO()
        w = codecs.getwriter(encoding)

        def append(name, obj):
            body.write(six.b('--{0}\r\n'.format(boundary)))

            # header
            w(body).write('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(name, obj.filename))
            body.write(six.b('\r\n'))
            if 'Content-Type' in obj.header:
                w(body).write('Content-Type: {0}'.format(obj.header['Content-Type']))
                body.write(six.b('\r\n'))
            if 'Content-Transfer-Encoding' in obj.header:
                w(body).write('Content-Transfer-Encoding: {0}'.format(obj.header['Content-Transfer-Encoding']))
                body.write(six.b('\r\n'))
            body.write(six.b('\r\n'))

            # body
            if not obj.data:
                with open(obj.filename, 'rb') as f:
                    body.write(f.read())
            else:
                data = obj.data.read()
                if isinstance(data, six.text_type):
                    w(body).write(data)
                else:
                    body.write(data)

            body.write(six.b('\r\n'))

        for k, v in self.__p['formData']:
            body.write(six.b('--{0}\r\n'.format(boundary)))

            w(body).write('Content-Disposition: form-data; name="{0}"'.format(k))
            body.write(six.b('\r\n'))
            body.write(six.b('\r\n'))

            w(body).write(v)

            body.write(six.b('\r\n'))

        # begin of file section
        for k, v in six.iteritems(self.__p['file']):
            if isinstance(v, list):
                for vv in v:
                    append(k, vv)
            else:
                append(k, v)

        # final boundary
        body.write(six.b('--{0}--\r\n'.format(boundary)))

        return content_type, body.getvalue()
465110
def to_email_attachment(self, filename, filedata, **kw):
        
        maintype = "application"
        subtype = "octet-stream"

        mime_type = mimetypes.guess_type(filename)[0]
        if mime_type is not None:
            maintype, subtype = mime_type.split("/")

        attachment = MIMEBase(maintype, subtype, **kw)
        attachment.set_payload(filedata)
        encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition",
                              "attachment; filename=%s" % filename)
        return attachment
294596
def base64ToImage(imgData, out_path, out_file):
        
        fh = open(os.path.join(out_path, out_file), "wb")
        fh.write(imgData.decode('base64'))
        fh.close()
        del fh
        return os.path.join(out_path, out_file)
545506
def compose_data(params=None, files=None):
    
    data = aiohttp.formdata.FormData(quote_fields=False)

    if params:
        for key, value in params.items():
            data.add_field(key, str(value))

    if files:
        for key, f in files.items():
            if isinstance(f, tuple):
                if len(f) == 2:
                    filename, fileobj = f
                else:
                    raise ValueError('Tuple must have exactly 2 elements: filename, fileobj')
            elif isinstance(f, types.InputFile):
                filename, fileobj = f.filename, f.file
            else:
                filename, fileobj = guess_filename(f) or key, f

            data.add_field(key, fileobj, filename=filename)

    return data
587517
private static MultipartFormData parseMultipart(UploadSetting uploadSetting) throws IOException {
		MultipartFormData formData = new MultipartFormData(uploadSetting);
		formData.parseRequest(getServletRequest());

		return formData;
	}
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
700064
def from_image(cls, image, partname):
        
        return ImagePart(partname, image.content_type, image.blob, image)
437656
function sendImg ({ path, res }) {
  res.writeHead(STATUS_OK, {
    'Content-Type': 'image/png'
  })
  fs.createReadStream(path).pipe(res)
}
1102349
function parseHttpBody(req, cb) {
	// check for multipart streams that can contain file uploads

	var contentType = req.headers['content-type'];
	var m = contentType && contentType.match(/^multipart\/form-data; boundary=(.+)$/);

	if (m && m[1]) {
		parseMultipart(req, m[1], cb);
	} else {
		parseSinglepart(req, cb);
	}
}
412531
def _build_multipart(cls, data):
        
        boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
        sep_boundary = b'\n--' + boundary
        end_boundary = sep_boundary + b'--'
        end_items = end_boundary, b"\n",
        builder = functools.partial(
            cls._build_part,
            sep_boundary=sep_boundary,
        )
        part_groups = map(builder, data.items())
        parts = itertools.chain.from_iterable(part_groups)
        body_items = itertools.chain(parts, end_items)
        content_type = 'multipart/form-data; boundary=%s' % boundary.decode('ascii')
        return b''.join(body_items), content_type
1294440
def parse_uploaded_image(field):
    ''''''
    args = image_parser.parse_args()

    image = args['file']
    if image.mimetype not in IMAGES_MIMETYPES:
        api.abort(400, 'Unsupported image format')
    bbox = args.get('bbox', None)
    if bbox:
        bbox = [int(float(c)) for c in bbox.split(',')]
    field.save(image, bbox=bbox)
1098782
function (obj) {
        var formData = new FormData();
        _.forOwn(obj, function (value, key) {
            _.isArray(value) ? _.forEach(value, function (eachValue) {
                formData.append(key, eachValue)
            }) : formData.append(key, value);
        });
        return {
            body: formData
        };
    }