I am developig a website using laravel. here i need to upload photos in different folder chossed by user. Here i think i need to know all the folder names inside image folder. Is there any way in laravel to read all folder names inside image folder.
I have done that.
$foler_names = [];
$i = 0;
$dir = public_path().'/img/gallery_img/';
$dirList = scandir($dir);
foreach ($dirList as $key => $value) {
if (strpos($value, '.') !== false) {
}else {
$foler_names[$i] = $value;
echo $value;
echo '</br>';
$i++;
}
}
You can use Storage facade for it.
$directories = Storage::directories($directory);
// Recursive...
$directories = Storage::allDirectories($directory);
Check the details here https://laravel.com/docs/5.8/filesystem#directories
Related
This question already has an answer here:
File uploading in Laravel
(1 answer)
Closed 3 years ago.
Been working on this problem for 2 days and still cannot figure it out. I am trying to upload multiple files into storage in my Laravel project. I know my code works up to the foreach as I tested this with dd.
My controller:
$files = $request->file('current_plan_year_claims_data_file_1');
$folder = public_path(). "\storage\\$id";
if (!File::exists($folder)) {
File::makeDirectory($folder, 0775, true, true);
}
if (!empty($files)) {
foreach($files as $file) {
Storage::disk(['driver' => 'local', 'root' => $folder])->put($file->getClientOriginalName(), file_get_contents($file));
}
}
I see that you are trying to store the files directly in public folder, but why not use the Storage API of Laravel and use the public disk? You can do something like this to upload the files to the public directory:
$id = 123;
$files = $request->file();
$folder = $id;
if (count($files) > 0) {
foreach ($files as $file) {
$file->store($folder, ['disk' => 'public']);
}
}
And be sure that you have linked the storage path to public:
php artisan storage:link
Focus on $files = $request->file(); line. When you don't pass an argument to file() method, all uploaded file instances are returned. Now when you will loop over the $files array, you will get access to individual uploaded files.
And then you can store the file using your logic, i.e. you can use the original name or whatever else. Even you can use the Storage facade to process the file instance.
i.e. if you want to store the files with their original names, I find this a cleaner way rather than what you are doing:
$id = 123;
$files = $request->file();
$folder = $id;
if (count($files) > 0) {
foreach ($files as $file) {
Storage::disk('public')->putFileAs(
$folder,
$file,
$file->getClientOriginalName()
);
}
}
And as suggested by #cbaconnier, you can use allFiles() method too that's more descriptive:
$files = $request->allFiles();
I hope this helps.
You're trying to iterate over files, and file is just a reference to request->file(), which is a SINGLE UploadedFile object.
As indicated by your comment, you have multiple file inputs with different name attributes, so you can't easily loop over them with one statement, eg: if you had multiple files all uploaded as "attachments[]" as the input name attribute, you could get them all with $request->allFiles('attachments'), however, if you want to keep the input names as they are, this should be close to what you want.
public function foo(Request $request, $id){
$folder = public_path(). "\storage\\$id";
if (!File::exists($folder)) {
File::makeDirectory($folder, 0775, true, true);
}
$files = array();
$files[] = $request->file('current_plan_year_claims_data_file_1');
$files[] = $request->file('prior_plan_year_claims_data_file_1');
$files[] = $request->file('etc_file_whatever');
foreach($files as $file) {
Storage::disk(['driver' => 'local', 'root' => $folder])->put($file->getClientOriginalName(), file_get_contents($file));
}
}
Side note, i'm not sure what you're doing with File and public_path, but if your goal is just to put something in your app storage, something like this should work fine
public function foo(Request $request, $id){
if(!\Storage::exists($id)){
\Storage::makeDirectory($id);
}
$files = array();
$files[] = $request->file('current_plan_year_claims_data_file_1');
$files[] = $request->file('prior_plan_year_claims_data_file_1');
$files[] = $request->file('etc_file_whatever');
foreach($files as $file) {
\Storage::put("$id/" . $file->getClientOriginalFileName(), $file);
}
}
Convert file name before force download.
I am trying to be able to convert the file name of the stored file name to the orignal file name before download
So when user clicks on a file to download instead of showing
post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php
Like in image below
It will just rename the downloaded file something like
config.php
Question how to only change the downloaded filename when click on image.
public function downloads($id) {
$this->db->where('attachment_id', $id);
$query = $this->db->get('attachments');
if ($query->num_rows() == 0) {
return false;
}
$path = '';
$file = '';
foreach ($query->result_array() as $result) {
$path .= FCPATH . 'uploads/';
// This gives the stored file name
// This is folder 201702
// Looks like 201702/post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php
$stored_file_name .= $result['attachment_name'];
// Out puts just example "config.php"
$original .= $result['file_name'];
}
force_download($path . $stored_file_name, NULL);
}
How about that
(imho your foreach loop doesn't make any sense)
public function downloads($id) {
$this->db->where('attachment_id', $id);
$query = $this->db->get('attachments');
if ($query->num_rows() == 0) {
return false;
}
$path = '';
$file = '';
foreach ($query->result_array() as $result) {
$path .= FCPATH . 'uploads/';
// This gives the stored file name
// This is folder 201702
// Looks like 201702/post_1486965530_jeJNHKWXPMrwRpGBYxczIfTbaqhLnDVO.php
$stored_file_name .= $result['attachment_name'];
// Out puts just example "config.php"
$original .= $result['file_name'];
}
force_download("your_filename.txt",file_get_contents($path . $stored_file_name));
}
Simple like that!
force_download(
$filenameWithFileExtension,
file_get_contents($fileToDownload),
mime_content_type($fileToDownload)
);
For this situation use force_download() something like this -
$file_name = "using md5 to convert it on normal text and stroe variable";
$file_path = "It's your file path, where have file in your drive"
$file_path = 'uploads/'.$path;
force_download($file_name, file_get_contents($file_path));
It's simple and working fine. Just need to store your file path and file name store in 2 different variables and pass them in force_download().
Hope it's work.
Good Luck.
I want to show all images that are in a particular folder, I have the folder path but I do not see how the number of images there are inside and how show all. Someone could help me?
If your files are inside public or a subfolder of it, this is is a way:
foreach (File::allFiles(public_path().'/assets/img/') as $file)
{
$filename = $file->getRelativePathName();
echo HTML::image('public/assets/img/'.$filename, $filename);
}
This is a router you can use to test it:
Route::any('images', function() {
$images = '';
foreach (File::allFiles(public_path() . '/assets/img/') as $file)
{
$filename = $file->getRelativePathName();
$images .= HTML::image('public/assets/img/'.$filename, $filename);
}
return "<htm><body>$images</body></htm>";
});
Edit the /assets/img/ to your own and just hit http://yourserver.dev/images.
I've this code for handling uploaded multiple images. I want to upload and handle videos also. How can I check whether uploaded file is image or video? Please note that I want to handle multiple video files.
<?php
include('selectdb2.php');
if($_SERVER['REQUEST_METHOD'] == "POST")
if(isset($_FILES['file']))
{
$count = 0;
$errors= array();
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name )
{
$file_name = $key.$_FILES['file']['name'][$key];
$file_size =$_FILES['file']['size'][$key];
$file_tmp =$_FILES['file']['tmp_name'][$key];
$file_type=$_FILES['file']['type'][$key];
$enc_id= $_POST['form_id'].$_POST['name3'];
$md5folder = md5($enc_id);
$upload_path ="uploads/".$md5folder;
if(!is_dir($upload_path))
{
mkdir($upload_path, 0777, true);
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,$upload_path.'/'.$file_name);
}
}
.....
.....
?>
You have to check out extension of file name because you can not trust content type of uploaded file. It can spoof by clients. So you have create array list -also know as white list- for extension list of images and videos.
For instance:
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
I am developing a module of epaper in codeigniter(PyroCMS).
I want to know how can I upload multiple images ar once.
Can anyone guide me in uploading multiple images?
I tried but I only found code for uploading single image which I have already used in news module.
In the view file give this code for image upload:
echo form_label('Multi Images','',$label_attr);
echo form_upload($multi_photo_attr);
where
$multi_photo_attr = array(
'id' => "cat_multi_images",
'class' => "multi",
'name' => "cat_multi_images[]",
'maxlength' => "25",
'multiple' => "multiple"
);
Now you need to create a folder in the root directory where your photos will be uploaded.
After that in the controller's method you need to store the path to that folder in a variable.This variable will be used to upload the images in the folder.
Next,get the names of all the images in a array something like this:
foreach($_FILES["cat_multi_images"] as $key => $value)
{
$i=0;
foreach($value as $key1 => $value1)
{
$multi_photo_array[$i][$key] = $value1;
$i++;
}
After that for every array element,i.e.,for every image run the below code to upload it:
function UploadFile($files,$path)
{
$extensions = array('jpeg','JPEG','gif','GIF','png','PNG','jpg','JPG','pdf','PDF','ZIP','zip','rar','RAR','html','HTML','TXT','txt','doc','docx','DOC','DOCX','ppt','PPT','pptx','PPTX','xlsx','XLSX','xls','XLS','exe','EXE','mp3','MP3','wav','WAV','m4r','M4R','mpeg','MPEG','mpg','MPG','mpe','MPE','mov','MOV','avi','AVI',);
$destination = $path.$files["name"];
//print_r($destination);exit;
// GET FILE PARTS
$fileParts = pathinfo($files['name']);
$file_name = $files['name'];
$file_name_only = $fileParts['filename'];
$file_name_only = preg_replace('/[^a-zA-Z0-9]/','',$file_name_only);
$file_extention = $fileParts['extension'];
$Count = 0;
$destination = $path.$file_name_only.".$file_extention";
$file_name = $file_name_only.".$file_extention";;
// THIS SHOULD KEEP CHECKING UNTIL THE FILE DOESN'T EXISTS
while( file_exists($destination))
{
$Count += 1;
$destination = $path. $file_name_only."-".$Count.".$file_extention";
$file_name = $file_name_only."-".$Count.".$file_extention";
}
$fileextension='';
$filename='';
if(!empty($files))
{
$filename=$files['name'];
$fileextension=substr($filename,strpos($filename,".")+1);
if(in_array($fileextension,$extensions))
{
$uploadstatus=move_uploaded_file($files["tmp_name"],$destination);
if($uploadstatus)
{
return $file_name;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
Just copy the above code.It should work as it is made for a general case by me!You can copy that code in your model file and call it in the controller like this :
$pr_photo_data = $this->admin_model->UploadFile($value,$targetPath_images);
$photo_list[] = $pr_photo_data;
And then store every image in the database
foreach($photo_list as $image)
{
$pro_image["cat_multi_images"] = $image;
$pro_retId = $this->admin_model->add_multipic_cat($pro_image);
}
where
function add_multipic_cat($data)
{
$retId = $this->database->query_insert("photo", $data);
return $retId;
}
Be careful.Take care and do every step accurately
check this one
https://github.com/blueimp/jQuery-File-Upload/wiki/jQuery-File-Upload,---Multi-file-upload-with-CodeIgniter
Struggling To Use PyroCMS Files Library To Upload Multiple Files