I want to save file uploaded through form into a json file for this I need to get post data which is easily get through Request or Input class methods.
The problem is whenever I use Request or Input I can't get methods such as getClientOriginalName to get name of file and other parameters of file.
My FileController code is as below:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request; // this handles both for Input and Request as in laravel 5.1 documentation
use Illuminate\Support\Facades\Input; // though added some classes to get work
use Illuminate\Support\Facades\File; // though added some classes to get work
use Illuminate\Filesystem\Filesystem; // though added some classes to get work
class FileController extends Controller
{
public function index()
{
$files = $this->getAllData();
return view('document.index', compact('files'));
}
public function create()
{
return view('document.create');
}
public function store(Request $request)
{
$name = $request->input('title');
echo $name;
$file = $request->file('afile');
if($request->hasFile('afile')) {
$file = $request->file('afile');
print_r($file); // return array of uploaded as expected
$filename = $file->getClientOriginalName(); // not working
// or
$filename = Input::file('afile')->getClientOriginalName(); // not working
echo $filename;
}
// print_r($file);
// $data= array('title'=>$name, 'afile'=>$file);
// $this->create_entry($data);
// return redirect('document');
}
}
FYI my file upload is sucessful and has got file array as
Array ( [0] => Symfony\Component\HttpFoundation\File\UploadedFile Object ( [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => new_file_1.txt [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => text/plain [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0 [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0 [pathName:SplFileInfo:private] => E:\xampp\tmp\php5680.tmp [fileName:SplFileInfo:private] => php5680.tmp ) )
The only problem is I can't get methods of Symphon2 API though i used
use Input;
or
use Illuminate\Support\Facades\Input;
Every methods of Input are not working either to check its valid or not.
Every tutorial I refer or documentation from laravel 5 uses same as I have used in my code.
So any Kind of suggestion or solution is really appreciated.
the functions as used in this documentation are working but no other methods except than that.
Your missing the use statement for the Input facade. Add the following to your use statements.
use Illuminate\Support\Facades\Input;
You may try this:
$filename = $file->getClientOriginalName();
Since you have already used the following:
$file = $request->file('afile');
The file method returns an instance of Symfony\Component\HttpFoundation\File\UploadedFile and in this case, the instance is already cached in the $file variable.
Also to make sure the upload was successful you may check it using something like this:
if($request->hasFile('afile')) {
$file = $request->file('afile');
$filename = $file->getClientOriginalName() .'.'. $file->getExtension();
}
this works for me
\Input::file('file')->getClientOriginalName();
In your form open tag add 'files' => true
{!! Form::open(array('files' => true, ....)) !!}
In the controller check first if the file has been uploaded correctly
if (!Input::file('afile')->isValid())
{
// return error 50x
}
$filename = Input::file('afile')->getClientOriginalName();
can't apply method to non-object means that Input::file(...) returned null and therefore the file wasn't uploaded or it doesn't exists. Then, when you call ->getClientOriginalName() from a null value php throws an exception.
Related
I am using Symfony 3.4.8 and I try to create a form for uploading a file. I followed exact the Symfony document steps but got the error:
Controller "AppBundle\Report::uploadReport()" requires that you provide a value for the "$fileUploader" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
Here is part of my code, the rest are the same from the document except I changed the class name. Clearly when the function get called, there is no FileUploader argument passed into the function. If I remove the argument FileUploader $fileUploader, the page can load without throwing exception but it won't get the file. I am new to Symfony, how can I solve this problem?
/**
* #Route("/report/create-report/upload/", name="report_create")
*/
public function uploadReport(Request $request, FileUploader $fileUploader)
{
$report = new Report();
$form = $this->createForm(ReportType::class, $report);
$form->add('submit', SubmitType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// $file stores the uploaded PDF file
/** #var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $report->getReport();
$fileName = $fileUploader->upload($file);
$report->setBrochure($fileName);
//$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
// moves the file to the directory where brochures are stored
//$file->move(
// $this->getParameter('reports_directory'),
// $fileName
//);
// updates the 'brochure' property to store the PDF file name
// instead of its contents
//$report->setReport($fileName);
// ... persist the $product variable or any other work
}
return $this->render('report/createReport.html.twig', array(
'form' => $form->createView(),
));
}
I have seen the post but I cannot get that answer to work on my end as there is no such variable $container.
Last update: I gave up trying implement upload from scratch. I used the recommended bundle to make it work with minimum amount of coding.
the argument brochures_directory of your FileUploader.php service seems to be emtpy.
Did you specify it in service.yml?
Did you also add it in your config.yml ?
And then did you clear symfony cache after change ?
I'm trying to get an extension of a file during upload but I get an error that path info requires a string:
I have tried:
$path_parts = pathinfo($_FILES['evidence']['name']);
echo $path_parts['extension'];
How can extract file extension, for example jpeg, doc, pdf, etc.
If you are using yii2 kartik file input you can get the instance of yii\web\uploadedFile this way to:
$file = UploadedFile::getInstanceByName('evidence'); // Get File Object byName
// Then you can get extension by this:
$file->getExtension()
If you want to validate file as well then you can use FileValidator using adhoc role:
$validator = new FileValidator(['extensions' => ['png','jpg']]);
if( $validator->validate($file, $errors) ) {
// Validation success now you can save file using $file->saveAs method
} else {
// ToDO with error: print_r($errors);
}
It's better not use $_FILES directly in Yii2 since framework provides abstraction with a class yii\web\UploadedFile. There is also separate page in guide describing working with uploaded files.
There is an example with model.
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
As you can see, extension is extracted using extension property ($this->imageFile->extension).
There are more info about form settings, handling in controller, uploading multiple files. All this can be found by the link mentioned above.
I am making a test for uploading a file in Laravel 5.1 project.
One of the checking in validation method looks like this
//assuming $file is instance of UploadedFile class
if ( ! $file->isValid()) {
/*add errors and return*/
}
And I need to test this check.
The question is: How do I create an invalid uploaded file ?
(UploadedFile extends Symfony\Component\HttpFoundation\File class which extends SplFileInfo php class)
I often find it's helpful to look at the library source:
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/File/UploadedFile.php
You can see that the isValid method checks if $this->error === UPLOAD_ERR_OK, which is the default.
The only way to set error, since it's a private variable, is through the constructor:
public function __construct($path, $originalName, $mimeType = null, $size = null, $error = null, $test = false)
So when creating your $file object, just make sure to set $error to something. Here's all of the available error constants:
http://php.net/manual/en/features.file-upload.errors.php
So for example you could do this:
$file = new UploadedFile($path, $origName, $mimeType, UPLOAD_ERR_INI_SIZE, true);
The last parameter is needed when testing to disable checking that file was uploaded via HTTP (in case your test actually creates file)
I'm attempting to store the email address of any user who uploads a file into an "uploader_name" string variable. I've attempted using the following code whichout success - attempting to upload the file will result in a Class 'App\Http\Controllers\Auth' not found error message being thrown back. I know this is a pretty basic question, but I can't seem to find any answers which specifically work with Laravel 5.
This is what I'm trying to use currently without success.
$filelist->uploader_name = Auth::user()->email;
If it helps, here's the full function which saves some of the automatic information of the file.
public function store()
{
$filelist = new Filelist($this->request->all());
//store file details - thanks to Jason Day on the unit forum for helping with some of this
$filelist->name = $this->request->file('asset')->getClientOriginalName();
$filelist->file_type = $this->request->file('asset')->getClientOriginalExtension();
$filelist->file_size = filesize($this->request->file('asset'));
$filelist->uploader_name = Auth::user()->email;
$filelist->save();
// Save uploaded file
if ($this->request->hasFile('asset') && $this->request->file('asset')->isValid()) {
$destinationPath = public_path() . '/assets/';
$fileName = $filelist->id . '.' . $this->request->file('asset')->guessClientExtension();
$this->request->file('asset')->move($destinationPath, $fileName);
}
return redirect('filelists');
}
You get not found error, because you don't use the right namespace.
You can resolve this if you use the use keyword like this:
use Auth;
public uploadController {
...
}
Or you can use the full namespace:
$filelist->uploader_name = \Auth::user()->email;
You are getting Class 'App\Http\Controllers\Auth' not found error because you are not using the correct namespace:
There are two ways to resolve this:
By including use keyword in your controller
Example:
use Auth;
UploadController{
....
}
or by specifying the full namespace directly like so
$filelist->uploader_name = \Auth::user()->email;
I need to send an image to server via an ajax request and it gets through just fine
and in my controller I can just use $_FILES["image"] to do stuff to it.
But I need to validate the image before I save it.
And in the Yii this can be achieved by doing something like this
$file = CUploadedFile::getInstance($model,'image');
if($model->validated(array('image'))){
$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user_thumb/' . $model->username.'.'.$model->photo->extensionName);
}
But the problem is I don't have a $model, all I have is $_FILES["image"], now what should I put instead of the $model???
is there any other way where I can validate and save files without creating a model and just by Using $_FILES["image"]?
thanks for this awesome community... :)
Exists many ways how you can do upload. I want offer to you one of them.
1.You need to create model for your images.
class Image extends CActiveRecord {
//method where need to specify validation rules
public function rules()
{
return [
['filename', 'length', 'max' => 40],
//other rules
];
}
//this function allow to upload file
public function doUpload($insName)
{
$file = CUploadedFile::getInstanceByName($insName);
if ($file) {
$file->saveAs(Yii::getPathOfAlias('webroot').'/upload/user_thumb/'.$this->filename.$file->getExtensionName());
} else {
$this->addError('Please, select at least one file'); // for example
}
}
}
2.Now, need to create controller, where you will do all actions.
class ImageController extends CController {
public function actionUpload()
{
$model = new Image();
if (Yii::app()->request->getPost('upload')) {
$model->filename = 'set filename';
$insName = 'image'; //if you try to upload from $_FILES['image']
if ($model->validate() && $model->doUpload($insName)) {
//upload is successful
} else {
//do something with errors
$errors = $model->getErrors();
}
}
}
}
Creating a model might be overkill in some instances.
The $_FILE supervariable is part of the HTTP mechanism.
You can handle the copy by using the native PHP function move_uploaded_file()
$fileName = "/uploads/".myimage.jpg";
unlink($fileName);
move_uploaded_file($_FILES['Filedata']['tmp_name'], $fileName);
However, you lose the niceties of using a library that provides additional functionality and checks (eg file type and file size limitations).