duanke1286 2015-08-30 15:10
浏览 53

使用unlink时,PHP Mongodb GridFS无法打开流

Symfony2 REST API

Goal: Upload images, use ImageResize to re-shape them and save them to a folder. Load them up and push to Mongo GridFS and then delete saved ones in folder.

Issue: Using unlink after flushing to mongodb triggers an error as if i have used unlink before:

    Warning: file_get_contents(C:/Users/Nikola/Desktop/awesome/web\pictures\1366%20768_small.jpg): failed to open stream: No such file or directory

Note that if i don't use unlink everything goess fine.

GalleryController:

public function uploadAction(Request $request) {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-    Type, Accept");
    header ("Content-Type: application/json; charset=utf-8");

$response = new ResponseModel();

try {

    // Did we receive any files ?
    if( $request->files->count() === 0) {
        throw new CustomErrorException("No files received");
    }

    $pathsToDelete = [];
    $names = [];

    $files = $request->files;

    foreach ($files as $file) {
        /* @var $file UploadedFile */

        // Check mime type
        if(!($file->getMimeType() == 'image/jpeg' || $file->getMimeType() == 'image/png')) {
            throw new CustomErrorException("We are only accepting jpg and png files.");
        }

        //var_dump();


        // Perform image operations and save them to a temp folder

        // Create small image
        $imageManipulator = new ImageResize($file->getRealPath());
        $imageManipulator->resizeToHeight(200);
        $imageManipulator->resizeToWidth(200);
        $array = explode(".", $file->getClientOriginalName());
        $name = $array[0];
        $ext = $array[1];
        $pathSmall = 'pictures'.DIRECTORY_SEPARATOR.$name.'_small.'.$ext;
        $imageManipulator->save($pathSmall);

        // Create medium image
        $imageManipulator = new ImageResize($file->getRealPath());
        $imageManipulator->resizeToHeight(600);
        $imageManipulator->resizeToWidth(600);
        $array = explode(".", $file->getClientOriginalName());
        $name = $array[0];
        $ext = $array[1];
        $pathMedium = 'pictures'.DIRECTORY_SEPARATOR.$name.'_medium.'.$ext;
        $imageManipulator->save($pathMedium);

        // Create Large image
        $imageManipulator = new ImageResize($file->getRealPath());
        $imageManipulator->resizeToHeight(1024);
        $imageManipulator->resizeToWidth(1024);
        $array = explode(".", $file->getClientOriginalName());
        $name = $array[0];
        $ext = $array[1];
        $pathLarge = 'pictures'.DIRECTORY_SEPARATOR.$name.'_large.'.$ext;
        $imageManipulator->save($pathLarge);



        // Get locator
        $configDirectories = array($_SERVER['DOCUMENT_ROOT']);
        $locator = new FileLocator($configDirectories);

        // Create image
        $img = new Image();
        $img->setName($file->getClientOriginalName());
        $img->setFileSmall($locator->locate($pathSmall));
        $img->setFileMedium($locator->locate($pathMedium));
        $img->setFileLarge($locator->locate($pathLarge));



        // Save files to the database
        $dm = $this->get('doctrine_mongodb')->getManager();
        $dm->persist($img);
        $dm->flush();


        array_push($pathsToDelete, $locator->locate($pathSmall));
        array_push($pathsToDelete, $locator->locate($pathMedium));
        array_push($pathsToDelete, $locator->locate($pathLarge));

        array_push($names, $file->getClientOriginalName());
    }


    // Delete files after persisting
    foreach ($pathsToDelete as $p) {
        unlink($p);
    }

    //Load files from db
    foreach ($names as $n) {
        $image = $this->get('doctrine_mongodb')->getRepository('BlueAwesomeBundle:Image')
            ->findOneBy(['name' => $n]);

        //save them for testing
        file_put_contents($n, $image->getFileSmall64());
    }


    $response->setData(['success' => true]);
}
catch(CustomErrorException $e) {
    $response->setErr($e->getMessage());
}

return new JsonResponse($response);

}

Image

namespace Blue\AwesomeBundle\Document;


use Doctrine\ODM\MongoDB\Mapping\Annotations\Date;
use Doctrine\ODM\MongoDB\Mapping\Annotations\File;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Id;
use MongoId;

class Image
{

/**
 * @var MongoId $id
 */
protected $id;

/**
 * @var string $name
 */
protected $name;

/**
 * @var file $file_small
 */
protected $file_small;

/**
 * @var file $file_medium
 */
protected $file_medium;

/**
 * @var file $file_large
 */
protected $file_large;

/**
 * @var date $uploadDate
 */
protected $uploadDate;

/**
 * @var string $mimeType
 */
protected $mimeType;

/**
 * @var int $length
 */
protected $length;

/**
 * @var int $chunkSize
 */
protected $chunkSize;

/**
 * @var string $md5
 */
protected $md5;


/**
 * Get id
 *
 * @return id $id
 */
public function getId()
{
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 * @return self
 */
public function setName($name)
{
    $this->name = $name;
    return $this;
}

/**
 * Get name
 *
 * @return string $name
 */
public function getName()
{
    return $this->name;
}

/**
 * Set fileSmall
 *
 * @param file $fileSmall
 * @return self
 */
public function setFileSmall($fileSmall)
{
    $this->file_small = $fileSmall;
    return $this;
}

/**
 * Get fileSmall
 *
 * @return file $fileSmall
 */
public function getFileSmall()
{
    return $this->file_small;
}

/** Returns 64base representation
 * @return string
 */
public function getFileSmall64() {
    return $this->file_small->getBytes();
}

/**
 * Set fileMedium
 *
 * @param file $fileMedium
 * @return self
 */
public function setFileMedium($fileMedium)
{
    $this->file_medium = $fileMedium;
    return $this;
}

/**
 * Get fileMedium
 *
 * @return file $fileMedium
 */
public function getFileMedium()
{
    return $this->file_medium;
}

/** Returns 64base representation
 * @return string
 */
public function getFileMedium64() {
    return $this->file_medium->getBytes();
}

/**
 * Set fileLarge
 *
 * @param file $fileLarge
 * @return self
 */
public function setFileLarge($fileLarge)
{
    $this->file_large = $fileLarge;
    return $this;
}

/** Returns 64base representation
 * @return string
 */
public function getFileLarge64() {
    return $this->file_large->getBytes();
}

/**
 * Get fileLarge
 *
 * @return file $fileLarge
 */
public function getFileLarge()
{
    return $this->file_large;
}

/**
 * Set uploadDate
 *
 * @param date $uploadDate
 * @return self
 */
public function setUploadDate($uploadDate)
{
    $this->uploadDate = $uploadDate;
    return $this;
}

/**
 * Get uploadDate
 *
 * @return date $uploadDate
 */
public function getUploadDate()
{
    return $this->uploadDate;
}

/**
 * Set mimeType
 *
 * @param string $mimeType
 * @return self
 */
public function setMimeType($mimeType)
{
    $this->mimeType = $mimeType;
    return $this;
}

/**
 * Get mimeType
 *
 * @return string $mimeType
 */
public function getMimeType()
{
    return $this->mimeType;
}

/**
 * Set length
 *
 * @param int $length
 * @return self
 */
public function setLength($length)
{
    $this->length = $length;
    return $this;
}

/**
 * Get length
 *
 * @return int $length
 */
public function getLength()
{
    return $this->length;
}

/**
 * Set chunkSize
 *
 * @param int $chunkSize
 * @return self
 */
public function setChunkSize($chunkSize)
{
    $this->chunkSize = $chunkSize;
    return $this;
}

/**
 * Get chunkSize
 *
 * @return int $chunkSize
 */
public function getChunkSize()
{
    return $this->chunkSize;
}

/**
 * Set md5
 *
 * @param string $md5
 * @return self
 */
public function setMd5($md5)
{
    $this->md5 = $md5;
    return $this;
}

/**
 * Get md5
 *
 * @return string $md5
 */
public function getMd5()
{
    return $this->md5;
}


/**
 * (PHP 5 &gt;= 5.4.0)<br/>
 * Specify data which should be serialized to JSON
 * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
 * @return mixed data which can be serialized by <b>json_encode</b>,
 * which is a value of any type other than a resource.
 */
function jsonSerialize()
{
    return (object) [
        'id' => $this->id,
        'name' => $this->name,
        'file' => $this->getFileSmall64(),
        'mimeType' => $this->mimeType
    ];
}
}

Image.mongodb.yml

Blue\AwesomeBundle\Document\Image:
  type: document

  fields:
    id:
      id: true
    name:
      type: string
    file_small:
      type: file
    file_medium:
      type: file
    file_large:
      type: file
    uploadDate:
      type: date
    mimeType:
      type: string
    length:
      type: int
    chunkSize:
      type: string
    md5:
      type: string

SOLVED

The thing is that i tried to store multiple files in one image document. Well gridfs doesn't work that way, so the solution is to make an image Document that only stores 1 file. In my case i created 3 documents with different sizes with different subname field based on shared name field.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)