How to receive a File in Zend Framework 2 - php

I am using ZF2.
I am sending a file via a HTML form not generated by Zend/Form. Now I am trying to get that file as i would normally do with $_FILES. I tried the below PHP code but all I get in the print_r is Array ( [upload] => bnk.csv )
How do I get all the metadata such as temp_dir of that file???.... I am new to Zend so dont know if I am forced to create the form with Zend/Form which seems silly since I only have a file upload field thats a lot easier to manage directly from the view.
$request = $this->getRequest();
if($request->isPost()){
$post= array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
print_r($post);
}
<form id="upload" method="post" action="bnk/upload/csv" enctype="multipart/form-data">
<label for="upload">Upload CSV File</label>
<input type="file" name="upload" />
<input type="submit"/>
</form>

/* upload */
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination("folder for upload");
$upload->addValidator('Size',false, 1024 * 1024 * 5 ); //size limit
$upload->addValidator('Extension',false,'zip,rar'); //extension limit
$files = $upload->getFileInfo();
foreach($files as $file=>$info){
//if file is valid
if($upload->isValid($file)){
//confirm to upload
$upload->receive($file);
}
}
I use Zend_File_Transfer_Adapter_Http for uploading

Related

How to upload font file in Laravel

I have files like this font.ttf I need to upload them
HTML code:
<form action="{{ route('admin.settings.pdf.update') }}" method="post" enctype="multipart/form-data">
#csrf
<input type="file" name="file" accept=".ttf" required>
<button type="submit" class="button green">upload</button>
</form>
Controller:
public function updatePdfFont(Request $request)
{
$request->validate([
'file' => 'required|file',
]);
// dd($request->all());
// rename($request->file, "pdf_font.ttf");
$request->file->store('fonts', 'public');
}
// public disk is a custom one that goes files to public folder
The problem that I'm facing now when uploading font it uploaded with no extension like this wmRey4YaOLaldchlFV1l6GQylbZArc4xmyy2tXnL
The second thing I need is how can I rename the file before uploading it? like I want to rename file to pdf_font.ttf
before this line:
$request->file->store('fonts', 'public');
get the file extension like this:
$file_name = $file->'pdf_font'.getClientOriginalExtension();
Now store the file with the $file_name
In web applications, one of the most common use-cases for storing files is storing user uploaded files such as photos and documents. Laravel makes it very easy to store uploaded files using the store method on an uploaded file instance. Call the store method with the path at which you wish to store the uploaded file:
public function update(Request $request)
{
$path = $request->file('avatar')->store('avatars');
return $path;
}
https://laravel.com/docs/8.x/filesystem

getClientOriginalName() on null and $request->hasFile('image') not working

I'm working on uploading some text and image to database. I'm getting an error :
Call to a member function getClientOriginalName() on null
when below code is used:
$file = $request->file('image')->getClientOriginalName(); // 'image' is name in html form.
But $file = $request->input('image'); gets image name.
(also if($request->hasFile('image')) is not work (it returns FALSE).)
In my html,
<form method="post" action="/postupload" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="image">
</form>
In my controller,
public function upload(Request $request) {
$title = $request->input('title');
if($request->hasFile('image')) {
$file = $request->file('image')->getClientOriginalName();
$image->move(public_path('images'), $file);
$post = new Post();
$is_success = $post->addPost($title, $file);
}
}
When you access the uploaded file using the $request->file() method, it returns an instance of php's native SplFileInfo class. By looking at the php manual, you can see which methods are available on that class, check it out here: https://www.php.net/manual/en/class.splfileinfo.php
Also, take a look at the Laravel's docs: https://laravel.com/docs/5.8/requests#files
To further extend the answer: Should you need to do something with your file that the SplFileInfo cannot do, you can retrieve the newly uploaded file via the Storage Facade, which is built on top of the Flysystem package that will give you a ton of options for working with files. Start by reading up on the File Storage Larave'ls docs here: https://laravel.com/docs/5.8/filesystem#retrieving-files
Use instead of that
$request->file('upload_file');
var_dump($request->file('upload_file'));

Slim Image Cropper With Codeigniter

View
<form method="post" enctype='multipart/form-data' action="<?php base_url();?>edituserpic" name="form_editpic" id="form_editpic" class="avatar">
<div class="slim"
data-label="Drop your avatar here"
data-size="240,240"
data-ratio="1:1">
<input type="file" name="avatar" required />
</div>
<button type="submit">Upload now!</button>
</form>
Controller
public function edit_user_pic() {
$data['baseurl'] = $this->config->item('base_url');
// Pass Slim's getImages the name of your file input, and since we only care about one image, postfix it with the first array key
$image = $this->slim->getImages('avatar')[0];
*/
// Grab the ouput data (data modified after Slim has done its thing)
if ( isset($image['output']['data']) )
{
// Original file name
$name = $image['output']['name'];
// Base64 of the image
$data = $image['output']['data'];
}
}
I'm just stuck in server side how to save to get output image and save to database.
I am getting $name undefined. This mean output is empty.
If anyone used it and able to help that would be great.
If you've setup to use a different name than "slim", pass it along.
$images = Slim::getImages('avatar');
$image = $images[0];
It works for me.

Laravel 5 : the move() function doesn't save the uploaded image file

What I'm trying is to set an image uploader with Laravel 5.
Here is the form.
<form action="/edit/{{$id}}" method="POST" enctype="multipart/form-data">
{!! csrf_field() !!}
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="hidden" name="_method" value="PUT">
//There are other tags (including other input) here
<input type="file" name="pic" accept="image/*">
<input type="submit" value="Apply Changes">
</form>
Here is the controller function which will be run from the form above.
public function update($id)
{
$this->model->find($id)->fill($this->request->all())->save();
if ($this->request->hasFile('pic')) {
$file = $this->request->file('pic');
$name = $file->getClientOriginalName();
$file->move('assets/serviceimages/', $name);
}
return redirect('/blahblah');
}
As you might have noticed, this doesn't store the uploaded file under the assets/serviceimages/ directory, which is what I've been trying.
Basically I've been following this tutorial, but apparently I'm missing something and totally clueless about what it is, even after I had a look at the API documentation.
Inside of the if statement of the controller function, it was confirmed that the $file and $name had what I expected.
Therefore, I suspect that the problem lies in the move() function.
Any small piece of advice will be appreciated, since this is my first time that I've tried to set an uploader.
Permissions if you are on Linux. If that doesn't work try it this way:
$image = $request->file('pic');
$destinationPathImg = '/your path/images/';
if (!$image->move($destinationPathImg, $image->getClientOriginalName())) {
return 'Error saving the file.';
}
Also, this need to be added in ur ()
public function update(Request $request, $id)
I found having to use the Storage adapter to use the full file path worked for me.
$storageAdapter = Storage::disk('v1')->getDriver()->getAdapter()
$full_path_before = $storageAdapter->applyPathPrefix($oldPath);
$full_path_after = $storageAdapter->applyPathPrefix($newPath);
if (!File::exists($full_path_before)){
throw new \Exception("Error moving folders");
}
$move_files = $full_path_after !== $full_path_before;
if ($move_files){
File::move($full_path_before, $full_path_after);
}
Use This Method This Will Work 100%
if($request->hasFile('filename')){
$file = $request->filename;
$file_new_name = $file->move("upload/posts/", $file->getClientOriginalName());
$post->filename = $file_new_names;
}
Remember filename is your < img name="filename" >

Basic image upload in Joomla custom component

I am trying to add image upload function to my view where I am creating model. I tried many sample codes here but I can't get to full path to file. My code looks like this:
public function submit() {
jimport ( 'joomla.filesystem.file' );
// Check for request forgeries.
JRequest::checkToken () or jexit ( JText::_ ( 'JINVALID_TOKEN' ) );
// Initialise variables.
$app = JFactory::getApplication ();
$model = $this->getModel ( 'createaction' );
// Get the data from the form POST
$data = JRequest::getVar ( 'jform', array (), 'post', 'array' );
echo $data['image']; <-- here
$createdItem = $model->createItem ( $data );
if ($createdItem) {
$redirect = JRoute::_ ( 'index.php?option=com_akcehned&view=actions', false );
$this->setRedirect ( $redirect, "Akce byla vytvořena" );
} else {
echo "<h2>Omlouváme se, ale něco se stalo špatně</h2>";
}
return true;
}
Part of file input in xml:
<field
name="image"
type="file"
description="COM_AKCEHNED_FORM_DESC_CREATEACTION_IMAGE"
label="COM_AKCEHNED_FORM_LBL_CREATEACTION_IMAGE"
size="10"
accept="image/*" />
Where I tried to echo file file input I get just name (image_name.jpg and so) but I need fullpath right? I saw examples with ['tmp_name'] but It's not working for me.
I tried code like this:
$jinput = $app->input;
$files = $jinput->files->get('jform');
$file = $files['image'];
echo $file;
echo $file['tmp_name'];
But it's not working for me either. I just get empty values. Can someone give me working block of code where I get data from other inputs and fullpath to file for upload? It's for joomla 2.5, Thanks
You need to make sure the the form tag contains enctype attribute and that it is set to "multipart/form-data" if your are going to upload files.
eg
<form action="" method="post" enctype="multipart/form-data">
Also see: What does enctype='multipart/form-data' mean?
Did you try DPAttachments, it takes only three lines of code to integrate attachment support into your component.
if (JLoader::import('components.com_dpattachments.libraries.dpattachments.core', JPATH_ADMINISTRATOR)) {
echo DPAttachmentsCore::render('com_demo.item', $object->id);
}
Drag and drop and copy paste from your clipboard (no need to save the file to your hard disk) is supported. Perhaps you want to give it a try. If not here is a link to the Github repo how the upload function is implemented:
https://github.com/Digital-Peak/DPAttachments/blob/master/com_dpattachments/admin/models/attachment.php#L50
[I'm the author of this component]

Categories