How to save images with different names? - php

I'm dealing with a few issues regarding multiple images uploads. My project deals with a form the user inputs multiple images that save to a database, but first temporarily stores the images in a directory to show a preview of sorts. In my class, which deals with the uploading of the image I am trying to rename the images as seen below.
I uploaded seven images on the dropdown.
I see that all its images were stored in the database by one.
While it had to be stored under different names.
Controller
public function store(Product $product, Request $request)
{
$path = null;
if ($request->hasFile('file'))
{
$file = $request->file('file');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs($this->path, $fileName, 'public');
}
$gallery = Gallery::create([
'product_id' => $product->id,
'image' => $path,
]);
return response()->json($gallery);
}

$file = $request->file('file');
$name = date('YmdHi');
$extension = $name.$file->getClientOriginalExtension();
In controller , just replace it.

Related

How can upload videos and save and list in laravel website

I want to upload multiple videos to their site and want to list them there. Please give me a solution to how can manage this.
I want to save it in the database so that could list on the site.
This is my code but not working proper consuming more time to upload and the page is expired
$this->validate($request, [
'filename' => 'required',
'file' => 'mimes:mp4,ts|max:100040|required'
]);
dd($request->all());
if ($request->hasFile('file')) {
//upload file
$file = $request->file('file');
if(!empty($file) && $file != null)
{
$video_file = new VideoPost();
$fileExentsion = $file->extension();
$fileName = $file->getClientOriginalName();
$fileFullName = time()."_".$fileName;
$path = Str::slug($fileFullName).".".$fileExentsion;
$file->move(public_path('files/'), $path);
$fullpath = 'files/'.$path;
$video_file->file = $fullpath;
$video_file->file_name = $request->file_name;
$video_file->save();
}
}

Laravel Upload Multiple Images all records with same name and not moved files

I am new in Laravel and I develop a web application where someone can upload a car ad and other users can write comments bellow that. Instead of developing a simple CRUD application I thought about developing also a table that will be related to these ads and will store the photos. Up to this point, I have made the relations, I can show images and I have two problems: The first problem is that not all images are moved to storage/photos folder and the second problem is that all the records in the database have the same name. For example, if I want to upload images 1,2,3 then in the database all the files will have the name 1.
Bellow, you may find the store code. This code stores all the ads and also the images if they exist.
public function store(Request $request)
{
//
$this->validate($request, [
'name' => 'required',
'cc' => 'required',
'desc' => 'required',
'date' => 'required'
]);
$ad = new Ad;
$ad->name = $request->input('name');
$ad->cc = $request->input('cc');
$ad->desc = $request->input('desc');
$ad->date = $request->input('date');
$ad->user_id = auth()->user()->id;
$ad->save();
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
if ($check) {
foreach ($request->photos as $photo) {
$photo->move('storage/photos', $filename);
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
return redirect('/home')->with('success', 'ad + image created');
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
}
return redirect('/home')->with('success','ad created');
}
Thank you in advance!
1st mistake, you did looping twice
2nd mistake (you might not realize this) you didnt merge the filename and extension, this will cause an issue when you retrieving the image in blade
therefore correction on your code plus comment to explain it
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
$fullpath = $filename . '.' . $extension ; // adding full path
if ($check) {
// removing 2nd loop
$file->move('storage/photos', $fullpath); // you should include extension here for retrieving in blade later
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
return redirect('/home')->with('success', 'ad + image created');
}
From the documentation, if you want to put your file on storage instead of on public folder you need to put these few lines of code as below in the your controller class
<?php
...
use Illuminate\Support\Facades\Storage;
...
class YourController extends Controller{
...
// Automatically generate a unique ID for file name...
Storage::putFile('photos', new File('/path/to/photo'));
...
}
This command will put your file into storage folder

Using Intervention Image to resize an image in the storage folder

I have a function in my Laravel application that allows users to upload profile pictures to their profile.
Here is the method:
/**
* Store a user's profile picture
*
* #param Request $request
* #return void
*/
public function storeProfilePicture(User $user = null, Request $request)
{
$user = $user ?? auth()->user();
//Retrieve all files
$file = $request->file('file');
//Retrieve the file paths where the files should be moved in to.
$file_path = "images/profile-pictures/" . $user->username;
//Get the file extension
$file_extension = $file->getClientOriginalExtension();
//Generate a random file name
$file_name = Str::random(16) . "." . $file_extension;
//Delete existing pictures from the user's profile picture folder
Storage::disk('public')->deleteDirectory($file_path);
//Move image to the correct path
$path = Storage::disk('public')->putFile($file_path, $file);
// Resize the profile picture
$thumbnail = Image::make($path)->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
});
$thumbnail->save();
$user->profile()->update([
'display_picture' => Storage::url($path)
]);
return response()->json(['success' => $file_name]);
}
I am trying to use the Intervention Image library to resize the uploaded picture from the storage folder, but I always get the same error.
"Image source not readable", exception: "Intervention\Image\Exception\NotReadableException"
I have also tried with Storage::url($path) as well as storage_path($path)
Here below code work very well with the storage path, you can directly make thumb image from request and put anywhere as a desire path as follows.
Note that here I am not deleting previse stored files or directory as I am assuming that was done already.
$file = $request->file('file');
$path = "public/images/profile-pictures/{$user->username}/";
$file_extension = $file->getClientOriginalExtension();
$file_name = time(). "." . $file_extension;
// Resize the profile picture
$thumbnail = Image::make($file)->resize(50, 50)->encode($file_ext);
$is_uploaded = Storage::put( $path .$file_name , (string)$thumbnail ); // returns true if file uploaded
if($is_uploaded){
$user->profile()->update([
'display_picture'=> $path .$file_name
]);
return response()->json(['success' => $file_name]);
}
Happy coding

Generate a thumbnail of any upload file

I have a website where users upload document files. I want to display thumbnails of these documents. How can I display the first page of a document file as an image using codeigniter?
Below is the controller code:
public function do_upload()
{
require_once APPPATH . "php_include/authenticate.php";
$path = "uploads/file_attachment/";
if($_FILES['userfile']['name'] != ''){
$image = $_FILES['userfile']['name'];
$ext = pathinfo($image, PATHINFO_EXTENSION);
$filename = basename($image,'.'.$ext);
$filename = preg_replace("/[^a-zA-Z0-9]+/", "-", $filename);
$image = $filename.'.'.$ext;
move_uploaded_file($_FILES["userfile"]["tmp_name"],$path.$image);
$data = array(
'user_id' => $user_id,
'file' => $image,
);
$this->signupmodel->addfile($data);
}
}
This may be a bit of overkill for you but I described a bulletproof way to upload images. There are all kinds of ways where the extension (.jpg, .gif) does not match the image. Browsers have to do similar testing before rendering an image.
This code also chooses the most efficient image type to save it as and scales the image to multiple dimensions.
Stackoverflow: Scaling Images

Laravel Image Upload Issue

I am trying to upload an image using Laravel it is working to the point that the images are being successfully placed into the destination folder but when I try to view them within my IDE I am told they are corrupt and that netbeans cannot open them.
I am wondering if my upload process is causing this?
This is my code:
public function handleCreate(){
$book = new Book;
$book->title = Input::get('title');
$book->desc = Input::get('desc');
//Img uploading...
$destinationPath = '';
$filename = '';
if(Input::hasFile('cover')){
$file = Input::file('cover');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . "_" . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
}
$book->cover = $filename;
$book->save();
return Redirect::route('books')->with('msg', 'test');
}
Any help is much appreciated. I know the image is not corrupt before uploading as I can view on my desktop. The issue is only after uploading it.

Categories