Storing Image path using Laravel - php

I have a controller which handles the upload functionality of the music file. The controller uses this Laravel getID3 package to parse the metadata from the music file and store in the database.
My code looks like this
if($request->hasfile('songs')){
foreach ( $request->file('songs') as $key => $file){
$track = new getID3($file);
$tifo = $track->extractInfo();
$artistName = $track->getArtist();
$songName = $track->getTitle();
$albumName = $track->getAlbum();
$extension = $track->getFileFormat();
$thumbnail = $track->getArtwork(true);
$thumbnails = 'artwork-'.time().'.'.$thumbnail->getClientOriginalExtension();
$location = time() .uniqid().'.' . $extension;
$file->storeAs('public/songs',$location);
//$file->storeAs('public/sthumbs',$thumbnails);
$file = new MusicUpload();
$music_upload_file = new MusicUpload();
$music_upload_file->user_id = Auth::user()->id;
$music_upload_file->filename = $songName;
$music_upload_file->extension = $extension;
$music_upload_file->artistname = $artistName;
$music_upload_file->albumname = $albumName;
$music_upload_file->location = $location;
$music_upload_file->thumbnail = $thumbnails;
$music_upload_file->save();
}
}
What I want to do is to store both the music file as well as the thumbnail of the file in the database.
Here the $thumbnails will store the image in the specified folder but the image is unreadable, i.e. it has the same file size as the music and doesn't contain the artwork which is to be stored and retrieved.
If I don't include the $thumbnails part, the package default stores to the temp folder which is inaccessible to the controller.
So how do I write the code such that the thumbnail(artwork) of the music gets stored in the correct folder and it can display the output too.

You can store it to storage folder.
Storage::disk('public')->put($location,File::get($file));
Don't forget to run php artisan storage:link

Related

Laravel, How to Find Uploaded Files by Specific Pattern in The Files' Name?

first of all to explain what I mean by my question, when I upload my files to the local storage I save them the following way:
$files = $request->file('files');
if ($request->hasFile('files')) {
foreach ($files as $file) {
//Get filename with the extension
$fileNameWithExt = $file->getClientOriginalName();
//Filename to store example: lead_4_document.pdf
$fileNameToStore = 'lead_' . $lead->id . '_' . $fileNameWithExt;
//Upload image
$path = $file->storeAs('/user_uploads', $fileNameToStore);
$lead->uploadFile()->create(array('filename' => $fileNameToStore, 'file_url' => $path, 'lead_id' => $lead->id));
}
}
So essentially I prepend lead_ the lead id and another _ to whatever the file is originally called during upload. The problem I face now is that I need to retrieve the associated files according to my lead ids. Here is my attempt so far:
$searchParam = 'lead_'.$lead->id.'_';
//$fileNames = File::glob('storage/user_uploads/'.$searchParam.'*');
//$files = File::get($fileNames);
$allFiles = Storage::files('user_uploads');
dd($allFiles);
Just to clarify, the 'File::glob' way seems to work, though it only outputs the names of the files not the actual files as object, which is what I need.
Okay, so I took a step back and went about this whole associated uploaded file to lead relationship a different way. Here is how I did it, just in case anyone stumbles across this and find themselves in the same boat as me.
The file upload now does a couple of things:
//check if file(s) is present in the request
if ($request->hasFile('files')) {
//checks if a directory already exists for a given lead (by id)
if (Storage::exists('/leads/'.$request->lead_id)) {
//if yes set the directory path to the existing folder
$directory = '/leads/'.$request->lead_id;
}
else {
//if not create a new directory with the lead id
Storage::makeDirectory('/leads/'.$request->lead_id);
$directory = '/leads/'.$request->lead_id;
}
foreach ($files as $file) {
//Get filename with the extension
$fileNameWithExt = $file->getClientOriginalName();
//Filename to store example: lead_4_document.pdf
$fileNameToStore = 'lead_' . $lead->id . '_' . $fileNameWithExt;
//Upload image
//'/user_uploads'
$file->storeAs($directory, $fileNameToStore);
//$lead->uploadFile()->create(array('filename' => $fileNameToStore, 'file_url' => $path, 'lead_id' => $lead->id));
}
}
So essentially, instead of trying to put all files into a single folder then checking the individual files for the 'lead_##' prepend, I instead create a folder with the id of the lead, this I then use the following way in my view function:
$directory = '/leads/'.$lead->id;
if (Storage::exists($directory)) {
$files = File::files('storage/'.$directory);
}
else {
$files = '';
}
Simply checking if the directory exists with the given lead ID, then if there are files uploaded either assign it the content, or set it blank (this is used for displaying an 'attachments' section on my page if not empty).

Laravel retrieve images from database

I need to display the stored images in my view.I've used the below code to store image in db,
$file = Input::file('pic');
$img = Image::make($file);
Response::make($img->encode('jpeg'));
$picture = new Car;
$picture->cartype = Input::get('cartype');
$picture->price = Input::get('price');
$FileName = Input::file('pic')->getClientOriginalName();
$FilePath = public_path('') .'/images/'. $FileName;
$picture->name = $FilePath;
$picture->save();
In my controller( to retrieve image)
public function index()
{
$cars = DB::table('car_category')->get();
return view('category.category',['cars'=>$cars]);
}
How should I retrieve and display the images in view?
If you are storing the image name in the database and uploading it in a directory then you can easily display it by simply fetching the name from database, returning the name to view and append the name to a hard-coded directory address like this -
<img src="/images/{{ $imageVariableName }}">
Let me know if this works.

CodeIgniter - error trying to view uploaded pdf files

I'm having difficulty trying to view a pdf file outside of the webroot folder.
This is the view file - I'm grabbing the file id from the URL and then querying the db to get all the file info stored from the upload.
$fid = $_GET['fid'];
$query = $this->db->query("SELECT * FROM files WHERE FID = $fid");
$fileinfo = $query->result();
foreach ($fileinfo as $row)
{
$fname = $row->file_name;
$ftype = $row->file_type;
$fpath = $row->file_path;
$full_path = $row->full_path;
$raw_name = $row->raw_name;
$client_name = $row->client_name;
$file_ext = $row->file_ext;
$file_size = $row->file_size;
$is_image = $row->is_image;
$width = $row->image_width;
$height = $row->image_height;
$img_type = $row->image_type;
$img_size = $row->image_size_str;
$orig_name = $row->orig_name;
$created = $row->created;
}
Then I'm taking that info and passing it to the File_viewer_model using the following:
$this->load->model('File_viewer_model');
$this->File_viewer_model->getFileInfo($fname,$ftype);
The function in the model that receives the data is as follows:
function getFileInfo($fname,$ftype){
$path = '/home/sitename/uploads/' . $fname;
header('Content-Type: ' . $ftype);
header('Content-Length: ' . filesize($path));
readfile($path);
}
The problem is when I click on the link to open a new tab and try to display the file, I get the following error:
File does not begin with '%PDF-'.
The file is in a 777 permissions directory called uploads right outside of the webroot - I've been all over the web and there seems to be several methods to display a pdf file, none of which seem to work for me. Any help would be appreciated. Thanks!
Solved: The problem was I was passing a header_view page in the controller before the $this->load->view('file_viewer_view'); section.
The PDF viewer was trying to parse the header_view first before the header('Content-Type: application/pdf') code in the file_viewer_view and thus generating the error.
I removed everything from the controller before the $this->load->view('file_viewer_view'); and it works like a champ!
Hopefully, this will save someone several hours of banging your head against the wall like I experienced!

Drupal: Save a file from filesystem

I want to save a file, that I have created in the temp directory, into drupal. But file_save requests a file object but I have just the real path.
$imageId =file_save('/tmp/proj/media/cover.jpg']);
I think you're looking for the file_save_data function, or possibly file_unmanaged_save_data, instead of file_save().
file_save(stdClass $file) save a file object. You are trying to download a file.
You can do as
$file = '/tmp/proj/media/cover.jpg';
// Get the file size
$details = stat($file);
$filesize = $details['size'];
// Get the path to your Drupal site's files directory
$dest = file_directory_path();
// Copy the file to the Drupal files directory
if(!file_copy($file, $dest)) {
echo "Failed to move file: $file.\n";
return;
} else {
// file_move might change the name of the file
$name = basename($file);
}
// Build the file object
$file_obj = new stdClass();
$file_obj->filename = $name;
$file_obj->filepath = $file;
$file_obj->filemime = file_get_mimetype($name);
$file_obj->filesize = $filesize;
$file_obj->filesource = $name;
// You can change this to the UID you want
$file_obj->uid = 1;
$file_obj->status = FILE_STATUS_TEMPORARY;
$file_obj->timestamp = time();
$file_obj->list = 1;
$file_obj->new = true;
// Save file to files table
drupal_write_record('files', $file_obj);
I hope this will help you.

For loop over named folder to read each .txt filename and contents

The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>

Categories