Symfony MongoDb 用 FS 存储图片

时间:2021-10-01 02:42:05

Symfony MongoDb 用 FS 存储图片

使用Symfony

  1. DBmanage引用GitHub

  2. controllor(控制器)

    public function saveBooksSubmitAction(Request $Request)
    {
    try {
    if ($Request->files->get("img_id")) {
    $UploadedFile = $Request->files->get("img_id");
    $this->checkUploadedIsValid($UploadedFile);

    $new_book->setImgId($this->getUploadedImgId());
    $new_book->create_time = new \MongoDate();
    $new_book->save();

    $this->addFlash("success", "成功图书入库。");
    } else {
    throw new \ErrorException("您没有上传图片,请先上传图片!");
    }
    } catch (\Exception $Exception) {
    $this->addFlash('error', $Exception->getMessage());
    }
    return $this->redirectToRoute('library_list');
    }


    private function getUploadedImgId()
    {
    $FSManager = new FSManager();
    return $FSManager->getPhotoGridFS()->storeUpload("img_id");
    }


    private function checkUploadedIsValid($UploadedFile)
    {
    $file_type = $UploadedFile->getMimeType();//image/png,image/jpeg,image/gif
    if ($file_type != "image/jpeg" && $file_type != 'image/png' && $file_type != 'image/gif') {
    throw new \ErrorException("只能上传jpg gif png文件");
    }
    }

    //通过id显示图片流
    public function showPictureAction($img_id)
    {
    $FSManager = new FSManager();
    $collection = $FSManager->getPhotoGridFS();
    $logo = $collection->findOne(array('_id' => new \MongoId($img_id))); // 以_id为索引取得文件
    header('Content-type: image/jpg'); // 输出图片头
    $pic = $logo->getBytes(); // 输出数据流
    return new Response($pic);
    }
  3. FSManager(图片处理类)

    <?php
    namespace AppBundle\DBManager;


    use rayful\DB\Mongo\DBManager;

    class FSManager extends DBManager
    {
    protected function collectionName()
    {
    return '';
    }

    public function getPhotoGridFS()
    {
    return $this->getSpecifiedGridFS('photo');
    }

    public function getAttachGridFS()
    {
    return $this->getSpecifiedGridFS('attach');
    }

    public function getSpecifiedGridFS($fsName)
    {
    return self::db()->getGridFS($fsName);
    }

    }

使用原生的PHP

    public function uploadImg()
{
$conn = new \MongoClient();
$db = $conn->test;
$prefix = 'img';
$collection = $db->getGridFS($prefix);
$file_size=$_FILES['book_img']['size'];
if($file_size>200*1024) {
throw new \ErrorException("文件过大,不能上传大于200kb的文件");
}
$file_type=$_FILES['book_img']['type'];//image/png,image/jpeg,image/gif
if($file_type !="image/jpeg" && $file_type!='image/png' && $file_type!='image/gif'){
throw new \ErrorException("只能上传jpg gif png文件");
}
$book_img_id = $collection->storeUpload('book_img');
$book_img_id = strval($book_img_id );
return $book_img_id;
// $logo = $collection->findOne(array('_id'=>$book_img_id)); // 以_id为索引取得文件
// header('Content-type: image/png'); // 输出图片头
// $pic= $logo ->getBytes(); // 输出数据流
// return $pic;
}