API REST Symfony2
Цель: Загрузите изображения, используйте ImageResize, чтобы изменить их форму и сохранить их в папке. Загрузите их и нажмите на Mongo GridFS, а затем удалите сохраненные в папке.
Выпуск: С помощью разъединить после смывание на mongodb вызывает ошибку, как будто я использовал unlink раньше:
Warning: file_get_contents(C:/Users/Nikola/Desktop/awesome/web\pictures\1366%20768_small.jpg): failed to open stream: No such file or directory
Обратите внимание, что если я не использую unlink, то все хорошо.
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);
}
Образ
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 >= 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
Дело в том, что я пытался хранить несколько файлов в одном документе изображения. Хорошо, gridfs не работает таким образом, поэтому решение состоит в том, чтобы создать документ с изображением, который хранит только 1 файл. В моем случае я создал 3 документа с разными размерами с различным полем имени на основе поля общего имени.
Задача ещё не решена.
Других решений пока нет …