How to handle file upload in symfony? - symfony

im trying to upload diffrent types of files in symfony
$uploadedFile = $request->files->get('image');
Works good for handling with images, However i cannot use it with diffrent files than
$uploadedFile = $request->files->get('file');
dd($uploadedFile);
Whatever i send using this, dd method shows me null.
How can I upload files for example pdfs, docx etc. (diffrent than images)
I use vue on the frontend.

You should use createForm.
https://symfony.com/doc/current/controller/upload_file.html
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** #var UploadedFile $brochureFile */
$brochureFile = $form->get('brochure')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($brochureFile) {
$originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$brochureFile->move(
$this->getParameter('brochures_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
$product->setBrochureFilename($newFilename);
}

Related

Create file dynamically as File object and then publish

It's evidently a little more complicated to create a file dynamically in SS4
$folder = Folder::find_or_make('Cards');
$filename = 'myimage.jpg';
$contents = file_get_contents('http://example.com/image.jpg');
$pathToFile = Controller::join_links(Director::baseFolder(), ASSETS_DIR, $folder->Title, $filename);
file_put_contents($pathToFile, $contents);
$image = Image::create();
$image->ParentID = $folder->ID;
$image->Title = "My title";
$image->Name = $filename;
$image->FileFilename = 'Cards/' . $filename;
$image->write();
Member::actAs(Member::get()->first(), function() use ($image, $folder) {
if (!$image->isPublished()) {
$image->publishFile();
$image->publishSingle();
}
if (!$folder->isPublished()) {
$folder->publishSingle();
}
});
The above, creates the file as expected in /assets/Cards/myimage.jpg and publishes it fine
However all previews are blank, so it's obviously not finding the file:
Any idea what I missed in creating the Image object?
This should work:
$folder = Folder::find_or_make('Cards');
$contents = file_get_contents('http://example.com/image.jpg');
$img = Image::create();
$img->setFromString($contents, 'image.jpg');
$img->ParentID = $parent->ID;
$img->write();
// This is needed to build the thumbnails
\SilverStripe\AssetAdmin\Controller\AssetAdmin::create()->generateThumbnails($img);
$img->publishSingle();
FYI: $img->Filename no longer exists. An Image or File object have a File property, which is a composite field of type DBFile. This composite fields contains the filename, hash and a variant…
So you should use the composite field to address these fields.

Concrete5 - CMS :: Get all file inside a file manager folder programmatically

I have a folder structure likes this:
folder1
subfolder1
file1.pdf
file2.pdf
subfolder2
file3.pdf
file4.pdf
is there any way to retrieve all the pdf file's(programmatically) using the "folder1" id?
There is but make sure you don't go insanely deep with your folder structure, you don't want to go through hundreds of folders, hundreds of levels deep.
Here's the code
<?php
use Concrete\Core\Tree\Node\Type\FileFolder;
use Concrete\Core\File\FolderItemList;
// First grab the folder object
$folder = FileFolder::getNodeByName('Testing Folder');
if (is_object($folder)) {
$files = [];
// if we have a folder we need to grab everything inside and then
// recursively go through the folder's content
// if what we get is a file we list it
// otherwise if it's another folder we go through it as well
$walk = function ($folder) use (&$files, &$walk) {
$list = new FolderItemList();
$list->filterByParentFolder($folder);
$list->sortByNodeName();
$nodes = $list->getResults();
foreach ($nodes as $node) {
if ($node->getTreeNodeTypeHandle() === 'file'){
$files[] = $node->getTreeNodeFileObject();
} elseif ($node->getTreeNodeTypeHandle() === 'file_folder'){
$walk($node);
}
}
};
$walk($folder);
// we are done going through all the folders, we now have our file nodes
foreach ($files as $file) {
echo sprintf('%sfile name is %s and URL is %s%s', '<p>', $file->getTitle(), $file->getURL(), '</p>');
}
}

Customer Image Profile

Is there an easy way to handle user profile image?
I tried with VichUploaderBundle without success.
Save them in your folder with a unique name and store names in the database.
To upload an image you can use a FileType field in your form, documented here. You can use ImageType for form validation as I remember and here is some code which will save the file in a folder and save the filename in the database:
$user = new User();
$form = $this->createForm(UserForm::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$img = $user->getPhoto();
$fileName = md5(uniqid()).'.'.$img->guessExtension();
$user->setPhoto($fileName);
// Move the file to the directory where brochures are stored
$img->move(
$this->getParameter('user_image_directory'),
$fileName
);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
And when you want to display the img you display it in twig in a similar fashion, first you read the filename with $user->getPhoto() and send it to your template, i had some bug when I called user.getPhoto() from the template, maybe it was just me:
img src="{{ asset('media/users/') }}{{ filename }}"></div>

Forms: transform multiple uploaded files (multiple => true) to multiple entities

I have an entity called Image. It contains a file attribute. I have also a form to create new Image entities with a FileType field which admits multiple uploads (multiple => true).
In case the user uploads multiple files, I would like to create the corresponding Image entities. What/where is the smartest way/place to do that?
We can do this inside controller,
$request = Request::createFromGlobals();
$em = $this->getDoctrine()->getManager();
if($request->isMethod('POST')){
foreach($request->files as $uploadedFile) {
$name = 'yourname.jpg';
$file = $uploadedFile->move($directory, $name);
$image->setFile('yourname.jpg');
$image = new Image();
$em->persist($image);
$em->flush();
}
}
* Remember images will be saved in the table according to the order you put them in view :)

Adding images from an external gallery to a SilverStripe site via a BuildTask

I'm making a Silverstripe build task to get many images from an external gallery, and create/upload them into the /assets/images/gallery folder with the necessary database links to the GalleryPage.
So I load the list of Urls, display the images to the browser, now how do I save an image into the assets folder with the necessary GalleryPage database links?
class ImportGalleryTask extends BuildTask {
public function writeImage($data) {
//$data->Title
//$data->Filename
//$data->Url
//this is the external url that I can output as an image to the browser
//
// folder to save image is 'assets/images/gallery'
//
// ? save into folder and database and associate to PageImageBelongsToID ?
}
}
You can use copy to copy a remote file to your local filesystem. PHP must be configured to support allow_url_fopen though.
So, your resulting function might look like this:
/**
* #param $data
* #return null|Image return written Image object or `null` if failed
*/
public function writeImage($data)
{
// The target folder for the image
$folder = Folder::find_or_make('images/gallery');
// assuming that $data->Filename contains just the file-name without path
$targetPath = $folder->getFullPath() . $data->Filename;
// Check if an image with this name already exists
// ATTENTION: This will overwrite existing images!
// If you don't want this, you need to implement this differently
if(
file_exists($targetPath) &&
$image = Image::get()->where(array(
'"Name" = ?' => $data->Filename,
'"ParentID" = ?' => $folder->ID
))->first()
){
// just copy the new file over…
copy($data->Url, $targetPath);
// … and delete all cached images
$image->deleteFormattedImages();
// and we're done
return $image;
}
// Try to copy the file
if (!copy($data->Url, $targetPath)) {
return null;
}
// Write the file to the DB
$image = Image::create(array(
'Name' => $data->Filename,
'ParentID' => $folder->ID,
'Filename' => $folder->getRelativePath() . $data->Filename
));
$image->write();
return $image;
}

Resources