I am trying to insert the details of an uploaded file into a database table and I am getting the following error:
Fatal error: Call to undefined method Symfony\Component\Finder\SplFileInfo::getClientOriginalName()
How would I get the getClientOriginalName(), getClientOriginalName() and getFilename() of a file in Laravel5?
Below is the code I am using.
public function add()
{
$directory = public_path('xml');
$files = File::allFiles($directory);
foreach ($files as $file) {
$entry = new Xmlentry();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
}
}
I'm a bit confused why you have getClientOriginalName() in there because that's aimed at temporary file names that have been uploaded but File::allFiles() is getting files from a directory that already have fixed names.
In addition to my comments above, I wanted to add you can just use the SplFileInfo methods.
I've taken the liberty of removing original file name from the code and correcting the lack of assignment statement for the variable $extension.
To answer your question:
public function add()
{
$directory = public_path('xml');
$files = File::allFiles($directory);
foreach ($files as $file) {
$entry = new Xmlentry();
$entry->mime = $file->getType();
$entry->filename = $file->getFilename(). '.' . $file->getExtension();
$entry->save();
}
}
Related
I have some files that I store at /storage/app/public/clientA/files/*.pdf. I have models that I can use to access these, and I want users to be able to download multiple files by selecting them in Nova and then using an action. Here is my code for the action:
public function handle(ActionFields $fields, Collection $models)
{
$files = array();
foreach ($models as $file) {
$path = FileHelper::getPathFromUrl($file->url);
array_push($files, $path);
}
$zip_file = 'myfiles.zip';
$zip = new \ZipArchive();
if ($zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true)
{
foreach ($files as $item) {
$zip->addFile(public_path('storage/' . $item), $item);
}
$zip->close();
}
return Action::download($zip_file, $zip_file);
}
Also, here is my code for the getPathFromUrl method:
public static function getPathFromUrl ($url)
{
$path = '';
$url_path = parse_url($url, PHP_URL_PATH);
return substr($url_path, strpos($url_path, "/") + 1);
} // returns the format storage/clientA/files/fileName.pdf
My issue at the moment is that its generating an empty zip file. I'm guessing that my paths are wrong when I try and reference the files, but I don't know how to fix it. I've also tried accessing these locations using Storage::get and found that it can't see the files at valid locations (and yes, I have done Storage:link).
Can anyone give me some insight into what I need to change to my addFile to ensure that these pdfs get added to the zip file?
In my Laravel project I created a page to upload the files and I use the $file of laravel it works fine for some system only but for some system it shows an error as shown in image below.
Function I am using to upload files in model
public function add_document_sub_cert($req)
{
$subcontractor_id = $req['subcontractor_id'];
$reference_id = $req['reference_id'];
$files = $req->file("uploaded_doc0");
$i = 0;
foreach($files as $file){
$i++;
$ext = $file->guessClientExtension();
$name = $file->getClientOriginalName();
$file_name_1 = str_replace(".".$ext,"",$name);
$path = $file->storeAs('subcontractor/','avc'.$i.'.jpg');
if($path){
$document = new Document();
$document->doc_name = 'avc.jpg';
$document->module = 'subcontractor';
$document->reference_id = $reference_id;
$document->save();
}
}
}
Your error says that you didn't specify a filename. I see that your variable $file_name_1 is never used. Haven't you forgotten to use it somewhere?
Without knowing how your class Document works, it's impossible to tell you exactly where is the bug.
I wan't to write a function which auto autoloads :) models based on files in folder model. So the application has to scan folder for files, grep all .php files, remove . and .. "folders" and place them in autoload['model'] = array
This is my current code in autoload.php file
$dir = './application/models';
$files = scandir($dir);
unset($files[0]);
unset($files[1]);
$mods = '';
foreach ($files as $f){
if(glob('*.php') ){
$mods .= str_replace('.php','',"'".$f."',");
}
}
$autoload['model'] = $mods;
And i'm keep getting errors like
An uncaught Exception was encountered
Type: RuntimeException
Message: Unable to locate the model you have specified: 'admins','categories','companies','countries'
Filename: D:\wamp64\www\myapp\public_html\rest\system\core\Loader.php
Line Number: 344
It looks like the problem is that when i pass array to $autoload variable it threats whole array as one model. Can you guys help me fix my problem.
I would go for something like:
/application/config/autoload.php
autoload['model'] = array('autoload_models');
/application/models/Autoload_models_model.php
class Autoload_models_model extends CI_Model {
public function __construct(){
parent::__construct();
// Scan directory where this (Autoload_models_model.php) file is located
$model_files = scandir(__DIR__);
foreach($model_files as $file){
// Make sure we are not reloading autoload_models_model
// Make sure we have a PHP file
if(
strtolower(explode('.', $file)[0]) !== strtolower(__CLASS__) &&
strtolower(explode('.', $file)[1]) === 'php')
{
$this->load->model(strtolower($file));
}
}
}
}
This is the solution that worked for me. If you find any shorter or nicer code please let me know
$dir = './application/models';
$files = scandir($dir);
$models = array();
foreach ($files as $f){
$file_parts = pathinfo($f);
$file_parts['extension'];
$correct_extension = Array('php');
if(in_array($file_parts['extension'], $correct_extension)){
array_push($models, str_replace('.php','',$f));
}
}
$autoload['model'] = $models;
/* autoload model */
function iteratorFileRegex( $dir, $regex )
{
$files = new FilesystemIterator( $dir );
$files = new RegexIterator( $files, $regex );
$models = array();
foreach ( $files as $file )
{
$models[] = pathinfo( $file, PATHINFO_FILENAME ); // Post_Model
}
return $models;
}
$autoload['model'] = iteratorFileRegex( APPPATH . "models", "/^.*\.(php)$/" );
I am trying to get content of all the files in my directory and I am getting an error that says
ErrorException in Util.php line 114:
preg_match() expects parameter 2 to be string, array given
. Below is the code that I am using.
public function store(Request $request)
{
$directory = storage_path('app/xmlentries/uploads');
$files = File::files($directory);
foreach ($files as $file)
{
$contents = Storage::get($file);
dd($contents);
}
How would i get the contents of all my files in this folder?
Try this:
$directory = storage_path('app/xmlentries/uploads/');
foreach (glob($directory . "*") as $file) {
$fileContent = file_get_contents($file);
dd($fileContent); // change this per your need
}
Please note this will display the first file and then stop!
I have pdf files which are report cards of students.The report card names format is <student full name(which can have spaces)><space><studentID>.I need to download files.For this I have used the following code.
if(file_exists($folder_path.'/') && is_dir(folder_path)) {
$report_files = glob(folder_path.'/*'.'_*\.pdf' );
if(count($report_files)>0)
{
$result_data = '';
$result_data = rename_filenamespaces($report_files);
var_dump($result_data);//this shows the edited filename
foreach ($result_data as $file) {
if (strpos($file,$_GET['StudentID']) !== false) {
//code for showing the pdf docs to download
}
}
}
}
//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
$new_location = $location;
foreach ($location as $file) {
//check file has spaces and filename has studentID
if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
{
$new_filename = str_replace(" ","-",$file);
rename($file,$new_filename);
$new_location = $new_filename;
}
}
return $new_location;
}
The variable $result_data gives me the filename without spaces,but the for each loop is showing Warning:Invalid argument supplied for foreach(). But the filename is changed in the server directory immediately after running the function. This warning shows only for first time. I am unable to solve this.
$new_location = $new_filename;
$new_location is a array
$new_filename is a string
You have to use $new_location[$index]
or try
foreach ($new_location as &$file) {
...
...
$file = $new_filename;