Save and retrieve file in Laravel - php

I have difficulty understanding the file save and retrieval in Laravel. I managed to get the file saved into correct path
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
However not I want to create an a-tag to download the file, but cannot manage to get to download the file.
{{$filenameToStore}}
The file download but I get the error "Failed- Server Problem". I do not want to use a same link as these files are confidential and should not be able to be downloaded outside the app.

Something like that?
Step 1:
Create table files id | filename | user_id.
Step 2:
Create model File
Step 3:
Add file row in table.
$fileNameWithExt = $request->file('Agreement_file')->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention =$request->file('Agreement_file')->getClientOriginalExtension();
$filenameToStore = $fileName . '_' . $lab_id. '.'.$extention;
$request->Agreement_file->storeAs('agreements', $filenameToStore );
File::create([
'filename' => $filenameToStore,
'user_id' => Auth::id()
]);
Step 4:
Create controller method download.
public function download(){
$filename = $request->input('filename');
$file = File::where('user_id', Auth::id())
->where('filename', $filename)
->firstOrFail();
$path = Storage::path('agreements/' . $filename);
if(Storage::exists($path)){
return Response::download($path, $filename);
}
}
Step 5:
Replace your link:
{{$filenameToStore}}
Or you can build it based on the file ID.

Related

Laravel 8 - Image not deleted from storage + not updating when "Edit"

possible "duplicate": Laravel - Delete images from storage / update post
I want laravel to delete the old image and replace it with new uploaded image in the edit form. I tried doing this:
if( $request->hasfile('violationStatement') ) {
$destination = 'violations/' . $violation->violationStatement;
// Deletes the file if it exists
if( File::exists($destination) ) {
File::delete($destination);
}
$file = $request->file('violationStatement');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('violations/', $filename);
$violation->violationStatement = $filename;
}
$violation->update();
But the image is not deleted nor updating. In addition, I want to have a condition when I just want to edit data without uploading new image...
Here is the routing:
// Traffic Violations
Route::controller(TrafficViolationController::class)->group(function () {
Route::get('violations', 'index')->name('violations.index'); // Index page (DataTable)
Route::get('violations/create', 'create')->name('violations.create'); // The form for adding new records
Route::post('violations/create', 'store')->name('violations.store'); // Add new to DB
Route::get('violations/edit/{violation}', 'edit')->name('violations.edit'); // The form for editing records
Route::put('violations/edit/{violation}', 'update')->name('violations.update'); // Update record to DB
Route::get('violations/{violation}', 'destroy')->name('violations.destroy'); // Delete from DB
});
First make sure of namespace
use Illuminate\Support\Facades\File;
Then edit $violation->update() to $violation->save();
And if the path in public folder use this method public_path() as this
$destination = public_path('violations/' . $violation->violationStatement);
But if the path in storage folder use this method storage_path() as this
$destination = storage_path('violations/' . $violation->violationStatement);
I use Intervention\Image\Facades\Image for uploading image And Illuminate\Support\Facades\File For Manage Directories. below Code replace Pic If Exist. think now you have 123.jpg and you want replace it. it replace old pic with new one. if your image name is difference you can delete old one.
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
//Get Data Of uploaded pic
$file = $request->file('violationStatement');
$srcPath = $file->getRealPath();
$size = $file->getSize(); // if You Need Pic Size
$extension = $file->getClientOriginalExtension();
//Start Uploading
$Image = Image::make($srcPath);
$destPath = public_path("violations");
File::ensureDirectoryExists($destPath); // Check Directory Exist Or Make
$filename = time() . '.' . $extension;
$Image->save($destPath.'/'.$filename);
at last I suggest add some unique thing to Your Image Name because it may two user upload picture at Same Time!!! and One Picture replaced.

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/

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));

How to save the full path of file upload in php?

I am using Laravel and I have a form that uploading a file. And I want to save the full path of that file in my database. Do you know how?
if($request->hasFile('alternate_add_file_path')) {
$file = $request->file('alternate_add_file_path');
$destination = 'files/';
$extension = $file->getClientOriginalExtension();
$file_name = $getCreateDate . '_' . str_replace('/','_',$M_USER_NAME) . '.' . $extension;
$file->move($destination, $file_name );
}
This below is for the save into database
$M_FILE_PATH = $file_name;
I do not have an error though, just only the filename which saved into my database, not the full path.
To convert a relative path to an absolute one (server side) you can use realpath. Eg.
$fullpath = realpath($file_name);

Laravel 5 The file "" does not exist

I'm trying to upload a file. Heres my controller
if ($request->hasFile('photo')) {
$destinationPath = 'images/quizzes/'; // upload path
$extension = $file->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
$request['photo'] = $fileName;
$request['image_path'] = $destinationPath;
$file->move($destinationPath, $fileName); // uploading file to given path
$quiz = Quiz::create($request->all())
}else{
\Session::flash('flash_message_delete','Please select files to upload.');
return redirect()->back();
}
It gives me FileNotFoundException in File.php line 37:The file "" does not exist. This was working fine the other day, idk what happes..i try to interchange the arrangement like:
$destinationPath = 'images/quizzes/'; // upload path
$extension = $file->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
$request['photo'] = $fileName;
$request['image_path'] = $destinationPath;
$quiz = Quiz::create($request->all());
$file->move($destinationPath, $fileName); // uploading file to given path
I wont have error like this, and it save to the database, THE PROBLEM is the photo field instead of the $filename it has wierd /tmp/somestrings inserted.

Categories