Create an Attachment from a string or resource of binary data.

WARNING: Changes to the file handle after calling this method will *NOT* be recognized anymore.

@param string|resource $data
@param string          $contentType

@return Attachment
424323
public static function createFromBinaryData($data, $contentType = false)
    {
        if (\is_resource($data)) {
            $data = \stream_get_contents($data);
        }

        return new self($data, \base64_encode($data), $contentType);
    }
372008
public static function renderAs($data, string $content_type, array $options = []) {
		// clena up output buffer
		\Helper\Ob::cleanAll();
		Application::set('flag.global.__content_type', $content_type);
		Application::set('flag.global.__skip_layout', 1);
		header("Content-type: " . $content_type);
		if (!empty($options['output_file_name'])) {
			header('Content-Disposition: attachment; filename=' . $options['output_file_name']);
		}
		$options['extension'] = ($options['extension'] ?? '');
		switch ($content_type . $options['extension']) {
			case 'application/json':
				echo json_encode($data);
				break;
			case 'application/xml':
				if (is_array($data)) {
					echo array2xml($data);
				} else {
					echo $data;
				}
				break;
			case 'text/html':
				\Helper\Ob::start();
				require(Application::get(['application', 'path_full']) . 'Layout/blank.html');
				echo str_replace([
					'<!-- [numbers: document title] -->',
					'<!-- [numbers: document body] -->'
				], [
					\Layout::renderDocumentTitle(),
					$data
				], \Helper\Ob::clean());
				break;
			case 'text/htmlemail':
				\Helper\Ob::start();
				require(Application::get(['application', 'path_full']) . 'Layout/' . \Application::get('application.layout.email') . '.html');
				echo str_replace([
					'<!-- [numbers: document title] -->',
					'<!-- [numbers: document body] -->'
				], [
					'<title>' . ($options['title'] ?? '') . '</title>',
					$data
				], \Helper\Ob::clean());
				break;
			case 'text/htmlplain':
			default:
				echo $data;
		}
		exit;
	}
1192286
public function getFile($path, $contentType) {
        if (is_file($path)) {
            $response = new Response(file_get_contents($path));
            $response->headers->set('Content-Type', $contentType);
            $response->setCharset('UTF-8');
            return $response;
        }

        return new Response('', 404);
    }
1066705
public function addPart($body, $contentType = null, $charset = null)
    {
        return $this->attach((new Swift_MimePart($body, $contentType, $charset))->setEncoder($this->getEncoder()));
    }
121952
public static Attachment fromText( String content, MediaType mediaType ) {
        if( mediaType.isBinary() ) {
            throw new IllegalArgumentException( "MediaType must not be binary" );
        }
        return new Attachment( content, mediaType );
    }
659243
def from_data(cls, type, **data):
        
        try:
            return cls._types[type](**data)
        except KeyError:
            return cls(type=type, **data)
        except TypeError as e:
            error = 'could not create {!r} attachment'.format(type)
            raise TypeError('{}: {}'.format(error, e.args[0]))
67115
public static function createFromBase64Data($data, $contentType = false, $revpos = false)
    {
        return new self(\base64_decode($data), $data, $contentType, false, $revpos);
    }
1061179
protected function getContentObject(array $contenttype, array $values)
    {
        if (empty($contenttype['class'])) {
            return new Content($this->app, $contenttype, $values);
        }

        if (class_exists($contenttype['class'])) {
            $content = new $contenttype['class']($this->app, $contenttype, $values);

            if (!($content instanceof Content)) {
                throw new StorageException($contenttype['class'] . ' does not extend \\Bolt\\Content.');
            }

            return $content;
        }

        $msg = sprintf('The ContentType %s has an invalid class specified "%s". Unable to log the changes to its records', $contenttype['slug'], $contenttype['class']);
        $this->app['logger.system']->error($msg, ['event' => 'content']);

        throw new StorageException($msg);
    }
1284299
public function setFile(Swift_FileStream $file, $contentType = null)
    {
        $this->setFilename(basename($file->getPath()));
        $this->setBody($file, $contentType);
        if (!isset($contentType)) {
            $extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1));

            if (array_key_exists($extension, $this->mimeTypes)) {
                $this->setContentType($this->mimeTypes[$extension]);
            }
        }

        return $this;
    }
915512
public function setContentType($contentType)
    {
        if (is_bool(strpos($contentType, 'charset=')) && $this->charset) {
            $contentType .= '; charset=' . $this->charset;
        }
        
        $this->headers['Content-Type'] = $contentType;
        return $this;
    }
511390
public static Attachment create(@NonNull String data, @NonNull String type, @Nullable String folder, @Nullable String name) {
        return new Attachment(ContentData.create(data, type, name), folder, type);
    }
41617
protected function setBody($body, $contentType)
    {
        $message = $this->getSwiftMessage();
        $oldBody = $message->getBody();
        $charset = $message->getCharset();
        if (empty($oldBody)) {
            $parts = $message->getChildren();
            $partFound = false;
            foreach ($parts as $key => $part) {
                if (!($part instanceof \Swift_Mime_Attachment)) {
                    /* @var $part \Swift_Mime_MimePart */
                    if ($part->getContentType() == $contentType) {
                        $charset = $part->getCharset();
                        unset($parts[$key]);
                        $partFound = true;
                        break;
                    }
                }
            }
            if ($partFound) {
                reset($parts);
                $message->setChildren($parts);
                $message->addPart($body, $contentType, $charset);
            } else {
                $message->setBody($body, $contentType);
            }
        } else {
            $oldContentType = $message->getContentType();
            if ($oldContentType == $contentType) {
                $message->setBody($body, $contentType);
            } else {
                $message->setBody(null);
                $message->setContentType(null);
                $message->addPart($oldBody, $oldContentType, $charset);
                $message->addPart($body, $contentType, $charset);
            }
        }
    }
90473
public function setContentType($contentType)
    {
        $this->contentType = $contentType;

        $this->setHeader('Content-Type', $contentType . '; charset=' . $this->getCharset());

        return $this;
    }
671639
public static Image getImage(final String wicketId, final String contentType, final Byte[] data)
	{
		final byte[] byteArrayData = ArrayUtils.toPrimitive(data);
		return getImage(wicketId, contentType, byteArrayData);
	}
989428
public static <T extends File> T createFile(final SecurityContext securityContext, final byte[] fileData, final String contentType, final Class<T> t)
		throws FrameworkException, IOException {

		return createFile(securityContext, fileData, contentType, t, null, true);

	}
1355941
public function withContentType($contentType)
    {
        $contentType = $this->normalizeContentType($contentType);

        $contentType = explode(';', $contentType, 2);

        $this->type = $contentType[0];

        $contentType[0] .= ';' . (isset($contentType[1]) ? $contentType[1] : ' charset=utf-8');

        return $this->withHeader('Content-Type', $contentType[0]);
    }
1216330
public function create($contentOrName, $type = null, array $data = [])
    {
        // Check if container or name is defined
        if (!(
            $contentOrName instanceof Model\ContentInterface ||
            (is_string($contentOrName) && 0 < strlen($contentOrName))
        )
        ) {
            throw new InvalidOperationException("Excepted instance of ContentInterface or string.");
        }

        // Default type if null
        if (null === $type) {
            $type = $this->defaultType;
        }

        // New instance
        $container = $this->editor->getRepository()->createContainer();
        $container->setType($type);

        // Plugin creation
        $plugin = $this->editor->getContainerPlugin($type);
        $plugin->create($container, $data);

        // Create default row
        if (!$plugin instanceof CopyPlugin) {
            $this->editor->getRowManager()->create($container);
        }

        // Add to container if available
        if ($contentOrName instanceof Model\ContentInterface) {
            $count = $contentOrName->getContainers()->count();
            $container->setPosition($count);
            $contentOrName->addContainer($container);
        } else {
            $container->setName($contentOrName);
        }

        return $container;
    }