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
Hi I am trying to integrate Dropzone.js in my app and using Laravel Framework. I have a form with below code,
<form method="post" action="{{url('/example/fileupload')}}"
enctype="multipart/form-data" class="dropzone" id="my-awesome-dropzone">
#csrf
<input type="submit">
</form>
The laravel controller attached with this form has below code in which I am just trying to get the name if the image which is dropped in dropzone area,
public function fileupload(Request $request)
{
$file = $request->file('file');
$filename = $file->getClientOriginalName();
echo $filename;
}
After clicking submit button it shows me below error,
Call to a member function getClientOriginalName() on null
Dont know what I am doing wrong here, because when I try to run the same code with simple
<input type="file" name="file">
it shows me the name of the uploaded image file which I want. Any suggestion or fix? Thanks
Try changing the "Input" class for "Request" ... I believe it will work. The error is being reported because there is no method on the object you are calling.
public function fileupload(Request $request)
{
$file= $request->file('file');
$fileName = $image->getClientOriginalName();
echo $fileName;
}
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'));
I'm trying to give allowed extension so I did try this code but I get error say
Undefined index: files[]
$ly_formname = 'files[]';
$file_type = $_FILES[$ly_formname]['type']; //returns the mimetype
$allowed = array("image/jpeg", "image/gif", "application/pdf");
if(!in_array($file_type, $allowed)) {
$error_message = 'Only jpg, gif, and pdf files are allowed.';
$error = 'yes';
}
I changed my variable name and still get the message error
the form name is file[] in yii framework
public function run()
{
return Html::input('file', 'files[]', null, $this->getOptions());
}
the input code I have is :
<input type="file" id="contentFormFilesGallery" name="files[]"
multiple="multiple" title="Upload file" accept="image/*" data-upload-url=""
data-upload-drop-zone="#contentFormBody" data-upload-
progress="#contentFormFiles_progress" data-upload-
preview="#contentFormFiles_preview" data-upload-form="" data-upload-single=""
data-upload-submit-name="fileList[]" data-upload-hide-in-stream="" data-php-max-
file-uploads="20" data-php-max-file-uploads-message="Sorry, you can only upload
up to 20 files at once." data-max-number-of-files="50" data-max-number-of-files-
message="This upload field only allows a maximum of 50 files." data-ui-
widget="file.Upload" data-ui-init="1" style="display:none">
Change files[] to files.
By having multiple form elements with the same name, PHP will convert those to an array. You don't have to (and can't) treat them as an array in HTML.
So, if you have two input with the name files, you can access it as $_POST['files'] or $_GET['files'].
I want to upload an image with Zend Framework version 1.9.6. The uploading itself works fine, but I want a couple of other things as well ... and I'm completely stuck.
Error messages for failing to upload an image won't show up.
If a user doesn't enter all the required fields but has uploaded an image then I want to display the uploaded image in my form. Either as an image or as a link to the image. Just some form of feedback to the user.
I want to use Zend_ Validate_ File_ IsImage. But it doesn't seem to do anything.
And lastly; is there some automatic renaming functionality?
All ideas and suggestions are very welcome. I've been struggling for two days now.
These are simplified code snippets:
myform.ini
method = "post"
elements.title.type = "text"
elements.title.options.label = "Title"
elements.title.options.attribs.size = 40
elements.title.options.required = true
elements.image.type = "file"
elements.image.options.label = "Image"
elements.image.options.validators.isimage.validator = "IsImage"
elements.submit.type = "submit"
elements.submit.options.label = "Save"
TestController
<?php
class Admin_TestController extends Zend_Controller_Action
{
public function testAction ()
{
$config = new Zend_Config_Ini(MY_SECRET_PATH . 'myform.ini');
$f = new Zend_Form($config);
if ($this->_request->isPost())
{
$data = $this->_request->getPost();
$imageElement = $f->getElement('image');
$imageElement->receive();
//$imageElement->getValue();
if ($f->isValid($data))
{
//save data
$this->_redirect('/admin');
}
else
{
$f->populate($data);
}
}
$this->view->form = $f;
}
}
?>
My view just echo's the 'form' variable.
First, put this at the start of your script:
error_reporting(E_ALL);//this should show all php errors
I think the error messages are missing from the form because you re-populate the form before you display it. I think that wipes out any error messages. To fix that, remove this part:
else
{
$f->populate($data);
}
To show the uploaded image in the form, just add a div to your view template, like this:
<div style="float:right"><?=$this->image?></div>
If the image uploaded ok, then populate $view->image with an img tag.
As for automatic re-naming, no, it's not built in, but it's very easy. I'll show you how below.
Here's how I handle my image uploads:
$form = new Zend_Form();
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an image:')
->setDestination($config->paths->upload)
->setRequired(true)
->setMaxFileSize(10240000) // limits the filesize on the client side
->setDescription('Click Browse and click on the image file you would like to upload');
$image->addValidator('Count', false, 1); // ensure only 1 file
$image->addValidator('Size', false, 10240000); // limit to 10 meg
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');// only JPEG, PNG, and GIFs
$form->addElement($image);
$this->view->form = $form;
if($this->getRequest()->isPost())
{
if(!$form->isValid($this->getRequest()->getParams()))
{
return $this->render('add');
}
if(!$form->image->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
return $this->render('add');
}
if($form->image->isUploaded())
{
$values = $form->getValues();
$source = $form->image->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'someNameYouInvent';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '/www/yoursite/images/'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="/images/'.$new_image_name.'" />';
$form->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
First, have a look at the Quick Start tutorial. Note how it has an ErrorController.php that will display error messages for you. Also note how the application.ini has these lines to cause PHP to emit error messages, but make sure you're in the "development" environment to see them (which is set in public/.htaccess).
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
Second, ZF has a renaming filter for file uploads:
$upload_elt = new Zend_Form_Element_File('upload');
$upload_elt
->setRequired(true)
->setLabel('Select the file to upload:')
->setDestination($uploadDir)
->addValidator('Count', false, 1) // ensure only 1 file
->addValidator('Size', false, 2097152) // limit to 2MB
->addValidator('Extension', false, 'doc,txt')
->addValidator('MimeType', false,
array('application/msword',
'text/plain'))
->addFilter('Rename', implode('_',
array($this->_user_id,
$this->_upload_category,
date('YmdHis'))))
->addValidator('NotExists', false, $uploadDir)
;
Some of the interesting things above:
mark the upload as required (which your .ini doesn't seem to do)
put all the uploads in a special directory
limit file size and acceptable mime types
rename upload to myuser_category_timestamp
don't overwrite an existing file (unlikely, given our timestamp scheme, but let's make sure anyway)
So, the above goes in your form. In the controller/action that receives the upload, you could do this:
$original_filename = $form->upload->getFileName(null, false);
if ($form->upload->receive()) {
$model->saveUpload(
$this->_identity, $form->upload->getFileName(null, false),
$original_filename
);
}
Note how we capture the $original_filename (if you need it) before doing receive(). After we receive(), we do getFileName() to get the thing that the rename filter picked as the new filename.
Finally, in the model->saveUpload method you could store whatever stuff to your database.
Make sure your view also outputs any error messages that you generate in the controller: loading errors, field validation, file validation. Renaming would be your job, as would other post processing such as by image-magick convert.
When following lo_fye's listing I experienced problems with custom decorators.
I do not have the default File Decorator set and got the following exception:
Warning: Exception caught by form: No file decorator found... unable to render file element Stack Trace:
The Answer to this is that one of your decrators must implement the empty interface Zend_Form_Decorator_Marker_File_Interface
Also sometimes it happens to bug when using an ajax request. Try it without an ajax request and don't forget the multipart form.