I want to save uploaded file to '/home/user/images' folder.
Is there any way to do this?
My 1st try:
controller
public function save(Request $request) {
$file = $request->file('image');
$file_name = $file->getClientOriginalName();
$file_path = '/home/user/images';
$file->move($file_path, $file_name);
}
/////////////////////
My 2nd try:
filesystems.php
'disks' => [
..
'custom_folder' => [
'driver' => 'local',
'root' => '/home/user/images',
],
...
controller
public function save(Request $request) {
$file = $request->file('image');,
$file_name = $file->getClientOriginalName();
Storage::disk('custom_folder')->put($file_name, $file);
}
I'm sorry if there is anything I did wrong. I just started learning php and Laravel.
For now, I save the files in the 'public / images' file path. I will use these files in multiple projects in the future. So I thought of such a method but could not reach the result.
if($request->hasFile('image')){
$image = $request->image;
$image_new_name = $image->getClientOriginalName();
$image->move('storage/custom_folder/', $image_new_name);
}
"storage" folder can be found inside "public" folder; public/storage/custom_folder.
If you want it outside your server dir then create a symlink inside your project folder.
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);
}
}
i am trying to upload video on my laravel project it didn't uploading but when i am trying to upload images it will works perfectly
{
$request->validate([
'file' => 'required',
]);
$fileName = time();
$request->file->move(public_path('videos'), $fileName);
$fileupload = new FileUpload;
$fileupload->filename=$fileName;
$fileupload->save();
return response()->json(['success'=>'File Uploaded Successfully']);
}
Well I would store the file first so that the code would rather looks like:
public function uploadVideo(Request $request) {
$request->validate([
'file' => 'required',
]);
$filename = time();
/* Storing the file on the disk */
$request->file->storeAs('videos', $filename);
/* Recording the upload on the database */
$fileupload = new FileUpload;
$fileupload->filename = $filename;
$fileupload->save();
return response()->json(['success'=>'File Uploaded Successfully']);
}
Indeed, in your code, your are moving a file that isn't stored... It can't work fine.
I would suggests you to read more the documentation about File Storage as you would have to use a command to make a symlink :
php artisan storage:link
This Code save image in only one folder. I want to upload the image at the same time in two different folders,
example
folder-one
and
folder-two
my controler
protected function validator(array $data)
{
return Validator::make($data, [
'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
}
protected function create(array $data)
{
$photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
$data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);
return user::create([
'photo_jpeg' => $photo_jpeg,
]);
}
Please make sure these things. if you are going to update file on different location.
The folder must have the writtable permission.
Directory path should be defined absolute and point to correct location.
Now change verify the changes in code as follow.
$fileName = time() . '.' .$request->file('User_jpeg')->getClientOriginalExtension();
$storageLocation = '../../WEBSITE-FILE/TEAM/USER'; //it should be absolute path of storage location.
$request->file('User_jpeg')
->storeAs($storageLocation, $fileName);
$request->file('User_jpeg')
->storeAs($storageLocation . '/User_Profile_Image', $fileName);
Edits:
As per the requested current status, try this.
public function store(Request $request) {
$this->validate($request, [ 'image' => 'required|image|mimes:jpeg,png,jpg|max:2048', ]); $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('folder-a'), $input['image']);
$fileSrc = public_path('folder-a') . $input['image'];
$fileDest = public_path('folder-b') . $input['image'];
\File::copy($fileSrc, $fileDest);
Service::create($input);
return back()->with('success',' CREATED SUCCESSFULLY .');
}
In controller:
public function store(Request $request){
if($request->User_jpeg != ''){ //check file has selected
$file = $request->User_jpeg;
$path = base_path('public/folder-one/');
$filename = time() . '_' . $file->getClientOriginalName();
$file->move($path, $filename);
\File::copy($path.$filename,base_path('public/folder-two/'.$filename));
}
user::create([
'photo_jpeg' => $filename,
]);
}
In route file (web.php):
Route::post('save-image', 'YourController#store');
I am using below code to store the uploaded file
$file = $request->file($file_attachment);
$rules = [];
$rules[$file_attachment] = 'required|mimes:jpeg|max:500';
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->with('uploadErrors', $validator->errors());
}
$userid = session()->get('user')->id;
$destinationPath = config('app.filesDestinationPath') . '/' . $userid . '/';
$uploaded = Storage::put($destinationPath . $file_attachment . '.' . $file->getClientOriginalExtension(), file_get_contents($file->getRealPath()));
The uploaded files are stored in storage/app/2/filename.jpg
I want to show back the user the file he uploaded. How can i do that?
$storage = Storage::get('/2/filename.jpg');
I am getting unreadable texts. I can confirm that the file is read. But how to show it as an image to the user.
Hope i made my point clear.
Working Solution
display.blade.php
<img src="{{ URL::asset('storage/photo.jpg') }}" />
web.php
Route::group(['middleware' => ['web']], function () {
Route::get('storage/{filename}', function ($filename) {
$userid = session()->get('user')->id;
return Storage::get($userid . '/' . $filename);
});
});
Thanks to: #Boghani Chirag and #rkj
File not publicly accessible like you said then read file like this
$userid = session()->get('user')->id;
$contents = Storage::get($userid.'/file.jpg');
Assuming your file is at path storage/app/{$userid}/file.jpg
and default disk is local check config/filesystems.php
File publicly accessible
If you want to make your file publicly accessible then store file inside this storage/app/public folder. You can create subfolders inside it and upload there. Once you store file inside storage/app/public then you have to just create a symbolic link and laravel has artisan command for it.
php artisan storage:link
This create a symbolic link of storage/app/public to public/storage. Means now you can access your file like this
$contents = Storage::disk('public')->get('file.jpg');
here the file physical path is at storage/app/public/file.jpg and it access through symbolic link path public/storage/file.jpg
Suppose you have subfolder storage/app/public/uploads where you store your uploaded files then you can access it like this
$contents = Storage::disk('public')->get('uploads/file.jpg');
When you make your upload in public folder then you can access it in view
echo asset('storage/file.jpg'); //without subfolder uploads
echo asset('storage/uploads/file.jpg');
check for details https://laravel.com/docs/5.6/filesystem#configuration
Remember put your folder in storage/app/public/
Create the symbolic linksymbolic link to access this folder
php artisan storage:link
if you want to access profile images of 2 folder then do like this in your blade file
<img src="{{ asset('storage/2/images/'.$user->profile_image) }}" />
Laravel 8
Controller
class MediaController extends Controller
{
public function show(Request $request, $filename)
{
$folder_name = 'upload';
$filename = 'example_img.jpeg';
$path = $folder_name.'/'.$filename;
if(!Storage::exists($path)){
abort(404);
}
return Storage::response($path);
}
}
Route
Route::get('media/{filename}', [\App\Http\Controllers\MediaController::class, 'show']);
Can you please try this code
routes.php
Route::group(['middleware' => ['web']], function() {
Route::get('storage/storage_inner_folder_fullpath/{filename}', function ($filename) {
return Image::make(storage_path() . '/storage_inner_folder_fullpath/' . $filename)->response();
});
});
view file code
<img src="{{ URL::asset('storage/storage_inner_folder_fullpath/'.$filename) }}" />
Thanks
Try this:
Storage::disk('your_disk_name')->getDriver()->getAdapter()->applyPathPrefix('your_file_name');
Good Luck !
Uploaded like this
$uploadedFile = $request->file('photo');
$photo = "my-prefix" . "_" . time() . "." . $uploadedFile->getClientOriginalExtension();
$photoPath = \Illuminate\Support\Facades\Storage::disk('local')->putFileAs(
"public/avatar",
$uploadedFile,
$photo
);
and then access like this
<img src="{{ asset('storage/avatar/'.$filename) }}" />
Create Route:
Route::get('image/{filename}', 'HomeController#displayImage')->name('image.displayImage');
Create Controller Method:
public function displayImage($filename)
{
$path = storage_public('images/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
<img src="{{ route('image.displayImage',$article->image_name) }}" alt="" title="">
can You please try this
$storage = Storage::get(['type_column_name']);
I am using Laravel and Intervention to handle a file upload from the user, I have installed Intervention using Composer but when I try to use some of its functions I get this error message Class 'Intervention\Image\Facades\Image' not found I have checked my app.php file and I have added the correct lines of code to aliases and providers but now I am not sure what is the problem
Here is my function
public function postAvatarUpload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|max:3000|mimes:jpeg,jpg,png',
]);
$user = Auth::user();
$usersname = $user->username;
$file = $request->file('image');
// $ext = $file->getClientOriginalExtension();
$ext= Input::file('image')->getClientOriginalExtension();
$filename = $usersname . '.' . $ext;
if (Storage::disk('public')->has($usersname)) {
Storage::delete($usersname);
}
Storage::disk('public')->put($filename, File::get($file));
$path = public_path('app/public/'. $filename);
Auth::user()->update([
'image' => $path,
]);
$resizedImg = Image::make($path)->resize(200,200);
// $ext = $file->getClientOriginalExtension();
return redirect()->route('profile.index',
['username' => Auth::user()->username]);
}
You also need to import it at the top of the file, after the namespace. Since you say that you've set the facade up, all you need to do is:
use Image;
Add facade and provider as described in the documentation. Then run composer dumpauto -o command.
Then add use Image to your class, or use it like this:
$resizedImg = \Image::make($path)->resize(200,200);