Laravel upload file in different folder - php

public function upload(Request $request){
$user = User::findOrFail(auth()->user()->id);
$filename = time() . '.jpg';
$filepath = public_path('uploads/');
move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);
move_uploaded_file($_FILES['filename']['tmp_name'], public_path('uploads/newfolder').$filename);
echo $filepath.$filename;
}
How can I upload the same image into different folders.
I have tried the above code and it doesn't work in the other folder.

You can't run move_uploaded_file twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.
You must copy the file:
public function upload(Request $request){
$user = User::findOrFail(auth()->user()->id);
$filename = time() . '.jpg';
$filepath = public_path('uploads/');
move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);
// Note that here, we are copying the destination of your moved file.
// If you try with the origin file, it won't work for the same reason.
copy($filepath.$filename, public_path('uploads/newfolder').$filename);
echo $filepath.$filename;
}

use Illuminate\Support\Facades\Storage;
public function upload(Request $request){
$filename = time() . '.jpg';
$filepath = public_path('uploads/newfolder/');
$file = $request->file( "filename" );
Storage::putFileAs( $filepath, $file, $filename );
echo Storage::url( 'uploads/newfolder/'.$filename );
}

You should try this:
Try with copy upload folder image to new folder like:
use Illuminate\Support\Facades\File;
$imgUpload = File::copy(public_path().'/uploads/'. $filename, public_path().'/newfolder/'. $filename);

Related

How to upload a image using Slim Framework

I want to storage a image in server and save the path in MySQL, but i'm not finding a good code to do it.
I found this, but does not work:
$container = $app->getContainer();
$container['upload_directory'] = __DIR__ . '../uploads';
$app->post('/photo', function (Request $request, Response $response) use ($app) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['picture'];
if($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->write('uploaded ' . $filename . '<br/>');
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(),
PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
Somebody knows how to upload image and save the path in MySQL?
First you need a database connection for MySQL. Read more
Then create a table, e.g. files(id, path, filename)
To insert the record (after the upload) into the table, you could use an SQL statement as follows:
// ...
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('File uploaded: ' . $filename);
$row = [
'path' => $directory,
'filename' => $filename
];
$sql = "INSERT INTO files SET path=:path, filename=:filename;";
$pdo->prepare($sql)->execute($row);
// ...
return $response;
Please note that $response->write('...') will not work. It must be $response->getBody()->write('my content');.
Edit: Make sure that the uploads/ directory exists and the directory has write access. For example chmod -R 1777 uploads/

Lumen get public directory

I want to store an image file with response like
http://localhost/storage/image/someimage.jpg
But when tried to use storage_path it returned
/home/../../../someimage.jpg
here's what i tried
if ($request->hasFile('avatar_image')) {
$image = $request->file('avatar_image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = storage_path('images');
$image->move($destinationPath, $name);
$detail->update([
'avatar_image' => env('APP_URL').$destinationPath.'/'.$name
]);
}
Is there any way to get only the storage directory like /storage/image/...
so i can concat it with my app_url
so what i did was symlink my storage/images with public folder then put it like
if ($request->hasFile('avatar_image')) {
$image = $request->file('avatar_image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = storage_path('images');
$image->move($destinationPath, $name);
$file_path = env('APP_URL').'/public/images'.$name;
$detail->update([
'avatar_image' => $file_path
]);
}
it did works but dont know if its good enough

Image dose not move at folder path

I already given 777 permission to my images folder. Charts Table is also saving all record of image. I am going to attach table:charts structure here.
public function store(Request $request)
{
$input = $request->all();
$tradeID= Auth::user()->trade()->create($input);
if($file = $request->file('file'))
{
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Chart::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$tradeID->chart()->create($input);
}
Try to change destination path from relative to absolute
public function store(Request $request)
{
$input = $request->all();
$tradeID= Auth::user()->trade()->create($input);
if($file = $request->file('file'))
{
$name = time() . $file->getClientOriginalName();
$file->move( public_path() . '/images/', $name); // absolute destination path
$photo = Chart::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$tradeID->chart()->create($input);
}
try this
if($file = $request->file('file'))
{
$name = time() . $file->getClientOriginalName();
$path = $file->storeAs('images', $name,'public');
$photo = Chart::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
you can retreive the file with /storage/public/file_name or /file_name depending on where you told laravel to store the public files
You are not actually storing the file, you are actually moving a non-existent file.
What you might consider
You, most probably want to access uploaded file from public path. If so, you should store this file to particular folder in your storage directory and create a symlink to that directory in your public path.
Here's an example:
Storage::disks('public')->put($filename, $uploadedFile); // filename = 'images/imageFile.jpg'
This creates a file in your storage/app/public/images directory.
Then, you can create a symlink, laravel provide a simple command to do so.
php artisan storage:link
This creates a symlink to your public disk.
Then, you can access the image at http://your-site-server/storage/images/imageFile.jpg
Hope it helps.
$name = time().'.'. $file->getClientOriginalName(); //depends on ur requirement
$file->move(public_path('images'), $name);
Are you trying to move uploaded file or existing file ?
To move file you need to do:
File::move($oldPath, $newPath);
the old path and new path should include full path with filename (and extension)
To store an uploaded file you need to do:
Storage::disk('diskname')->put($newPath, File::get($file));
the new path is full path with filename (and extension).
disk is optional , you can store file directly with Storage::put()..
Disks are located in config/filesystems.php
The File::get($file) , $file is your input from post request $file = $request->file('file') , basically it gets contents of uploaded file.
UPD#1
Okay , you can do this:
$request->file('file')->store(public_path('images'));
Or with Storage class:
// get uploaded file
$file = $request->file('file');
// returns the original file name.
$original = $file->getClientOriginalName();
// get filename with extension like demo.php
$filename = pathinfo($original)['basename'];
// get public path to images folder
$path = public_path('images');
// concat public path with filename
$filePath = $path.'/'.$filename;
// store uploaded file to path
$store = Storage::put($filePath, File::get($file));

Image Upload is not working in a Laravel Project hosted in a shared server

I have deployed a Laravel project in a shared hosting. I have changed my .env file and copied all files from the public folder to the main directory and deleted the public folder. Now the problem is, whenever I am trying to upload an image, I am getting an internal server error. I suppose the problem is the Image Intervention is not getting the right folder to save the image. I have tried the both ways given below:
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('/images/admin/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
and
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = '/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
But None of these is working. Any possible Solution?
Use laravel base_path function, so your code will look like this
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = base_path().'/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
Answer Update
Issue was fileinfo extension missing or disbaled.
Try This.
use Storage;
use File;
if(!empty($request->file('admin_pro_pic')))
{
$file = $request->file('admin_pro_pic') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$admin->image=$fileName;
}
Create imges inside public directory.
I am handling it like this:
// check for defined upload folder inside .env file, otherwise use 'public'
$publicUploadDir = env('UPLOAD_PUBLIC', 'public/');
// get file from request
$image = $request->file('admin_pro_pic');
// hasing is not necessary, but recommended
$new['path'] = hash('sha256', time());
$new['folder] = 'images/admin/';
$new['extension'] = $file->extension();
// store uploaded file and retrieve path
$image->storeAs($publicUploadDir, implode($new, '.'));

Laravel - Create custom name while uploading image using storage

I am trying to upload a file using laravel Storage i.e
$request->file('input_field_name')->store('directory_name'); but it is saving the file in specified directory with random string name.
Now I want to save the uploaded file with custom name i.e current timestamp concatenate with actual file name. Is there any fastest and simplest way to achive this functionality.
Use storeAs() instead:
$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');
You can use below code :
Use File Facade
use Illuminate\Http\File;
Make Following Changes in Your Code
$custom_file_name = time().'-'.$request->file('input_field_name')->getClientOriginalName();
$path = $request->file('input_field_name')->storeAs('directory_name',$custom_file_name);
For more detail : Laravel Filesystem And storeAs as mention by #Alexey Mezenin
Hope this code will help :)
You also can try like this
$ImgValue = $request->service_photo;
$getFileExt = $ImgValue->getClientOriginalExtension();
$uploadedFile = time()'.'.$getFileExt;
$uploadDir = public_path('UPLOAS_PATH');
$ImgValue->move($uploadDir, $uploadedFile);
Thanks,
Try with following work :
$image = time() .'_'. $request->file('image')->getClientOriginalName();
$path = base_path() . '/public/uploads/';
$request->file('image')->move($path, $image);
You can also try this one.
$originalName = time().'.'.$file->getClientOriginalName();
$filename = str_slug(pathinfo($originalName, PATHINFO_FILENAME), "-");
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$path = public_path('/uploads/');
//Call getNewFileName function
$finalFullName = $this->getNewFileName($filename, $extension, $path);
// Function getNewFileName
public function getNewFileName($filename, $extension, $path)
{
$i = 1;
$new_filename = $filename . '.' . $extension;
while (File::exists($path . $new_filename))
$new_filename = $filename . '_' . $i++ . '.' . $extension;
return $new_filename;
}

Categories