欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

symfony访问web目录外的图片

程序员文章站 2022-07-03 15:40:03
...

在这里插入代码片
前台给img的src写路由
<img id=“title_preview” src={{ “img_src_in_check”"?path="imgPath }}>

后台Controller
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;

public function getPicAction(Request $request)

{

    $full_path = $request->get('path');
    $this->get('logger')->info(var_export($full_path,true));

    $fs = new FileSystem();
    if (!$fs->exists($full_path)) {
        throw $this->createNotFoundException();
    }

    $file_name = basename($full_path);
    $mime_type = $this->getMimeType($full_path);

    $file = readfile($full_path);
    $headers = array(
        'Content-Type'     => $mime_type,
        'Content-Disposition' => 'inline; filename="'.$file_name.'"');
    return new Response($file, 200, $headers);
}`

protected function getMimeType($file)
{

    if ('png' === substr($file, -3)) {
        $best_guess = 'png';
    } else {
        $guesser = MimeTypeGuesser::getInstance();
        $best_guess = $guesser->guess($file);
    }
    return $best_guess;
}