I wanted to ask what is it like to upload to a host and save it? Of course in the storage folder
Why does this source of mine upload in localhost but not in Host?
But it does not upload at all in the host.
public function store(Request $request)
{
$path = $request->file('image') ?? null;
if ($request->hasFile('image'))
{
$file = $request->file('image');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs('images/aboutExhibitions', $fileName, 'public');
}
AboutExhibition::query()->create([
'user_id' => auth()->id(),
'title' => $request->title,
'link' => $request->link,
'image' => $path,
'options' => $request->options,
'body' => $request->body,
]);
return redirect()->route('admin.aboutExhibitions.index');
}
In the meantime, when I was inside the localhost, I executed the following command before.
php artisan storage:link
Hope this will work.
$image = $request->image;
$image_name=uniqid().date('dmYhis');
$ext=strtolower($image->getClientOriginalExtension());
$image_full_name=$image_name.'.'.$ext;
$image_url=$upload_path.$image_full_name;
$success=$image->move($upload_path,$image_full_name);
$data = array();
$data['image']=$image_url;
$store = Custom::create($data);
Related
I need upload a image to Google storage and insert the below JSON object with the gcs image path in MongoDB.
The image is successfully getting uploaded in GCS, but I am not able to get the image url of the image and also not able to update the path in mongoDB.
JSON object format
{
"original": "/pictures/1620305924456-74535-605b8a97a02cf2c1",
"thumbnail": "/pictures/1620305924456-74535-605b8a97a02cf2c1",
"fileType": "image"
}
Can anyone help me to implement the this logic.
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$disk = Storage::disk('gcs');
$imagePath = $request->file('imageUrl');
$imageName = $imagePath->getClientOriginalName();
$disk->put('pictures', $request->file('imageUrl'));
$player->name ='test';
$player->imageUrl = [
'original' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
'thumbnail' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
'fileType'=> 'image'
];
Appreciation::create($player);
return redirect()->route('appreciation.index')
->with('success','Record created successfully.');
}
Thanks in advance
Finally I fixed it using below code .
request()->validate([
'name' => 'required',
'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$appreciation = new Appreciation();
$appreciation->name = $request->get('name');
$imagePath = $request->file('imageUrl');
$imageName = $imagePath->getClientOriginalName();
$disk = Storage::disk('gcs');
$url = $disk->url('/pictures/'.$imageName);
$disk->putFileAs('/pictures/', $request->file('imageUrl'), $imageName);
$data = [
'original' =>'/pictures/'.$imageName,
'thumbnail' => '/pictures/'.$imageName,
'fileType'=> 'image'
];
$appreciation->imageUrl = $data;
$appreciation->save();
I am working on xampp localhost. I have a laravel setup. and I am uploading a file from my project to another laravel project.
public function cvupload(Request $request)
{
$this->validate($request,[
'resume' => 'required|mimes:doc,pdf,docx'
],
[
'required' => 'This field is required',
'mimes' => 'Allowed only doc,pdf,docx',
]);
$image = $request->file('resume');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = 'http://example.com/adminapi/app/storage/uploads/';
$image->move($destinationPath, $name);
$resume_with_path = $destinationPath.$name;
}
i gives error
Symfony\Component\HttpFoundation\File\Exception\FileException Unable to create the directory.
I have recently started to work with laravel voyager admin package, and I have an issue about file upload mechanism.
Firstly, I have create a folder on media menu "contacts":
https://i.imgur.com/fkaVqBz.png
After that, I have made a controller to deal with the contact form and which they can upload their curriculum vitae:
https://i.imgur.com/ckCCSOH.png
In my ContactController, I have made some validations regarding the uploaded file, and some modifications on the name of the uploaded file if the user send the post request:
<?php
namespace App\Http\Controllers;
use App\Contact;
use Illuminate\Http\Request;
use App\Rules\Captcha;
class ContactController extends Controller
{
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function PostContact(Request $request) {
//
$this->validate($request, [
'nom' => 'required|min:2|max:50',
'prenom' => 'required|min:2|max:50',
'email' => 'required|email',
'organisme' => 'required',
'fonction' => 'required',
'pays' => 'required',
'ville' => 'required',
'telephone' => 'required|numeric|',
'objet' => 'required',
'fichier' => 'sometimes|nullable|mimes:doc,docx,pdf',
'g-recaptcha-response' => new Captcha(),
'message' => 'required|min:10']);
$contact = new Contact;
$contact->nom = $request->input('nom');
$contact->prenom = $request->input('prenom');
$contact->organisme = $request->input('organisme');
$contact->fonction = $request->input('fonction');
$contact->pays = $request->input('pays');
$contact->ville = $request->input('ville');
$contact->email = $request->input('email');
$contact->telephone = $request->input('telephone');
$contact->objet = $request->objet;
if ($request->hasFile('fichier')) {
$filenameWithExt = $request->file('fichier')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('fichier')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('fichier')->storeAs('contacts', $fileNameToStore);
$contact->fichier = $path;
}
$contact->message = $request->input('message');
$contact->save();
return redirect('contact')->with('status', 'Votre message a été envoyé avec succès !!');
}
}
The CV file is successfully uploaded but not in the right destination, and contacts folder is creation in storage\app:
https://i.imgur.com/YPpzfCD.png
https://i.imgur.com/KV2CNXo.png
When I create a new contact via voyager admin panel (contact bread)
https://i.imgur.com/Q3GBom8.png, the file uploaded goes into public\contacts\month-year-folder (May2019)\
and this is what I hope to do also using my contact form.
https://i.imgur.com/bFKSKzq.png
Can someone help me solving this issue?
PS: the command php artisan storage:link
indicate that the "public/storage" directory already exists.
Also, I will show any file content if needed
Thanks.
First add a new entry in disks section of config/filesystem.php file
'contacts' => [
'driver' => 'local',
'root' => public_path('contacts'),
'url' => env('APP_URL').'/contacts',
'visibility' => 'public',
],
Then in your controller change the line
$path = $request->file('fichier')->storeAs('contacts', $fileNameToStore);
to
Storage::disk('contacts')->putFileAs($monthYear, $request->file('fichier'), $filename)
Of course you have to calculate your $monthYear variable to compute the subfolder name.
Regarding #Leonardo Rossi's comment, I have resolved this issue by adding this into my config/filesystem.php:
'contacts' => [
'driver' => 'local',
'root' => storage_path('app/public/contacts'),
'url' => '/contacts',
'visibility' => 'public',
],
and in the controller, because the file was stored in the correct folder, I have tried to get the path and then store it in database field (fichier) like that:
if ($request->hasFile('fichier')) {
$filenameWithExt = $request->file('fichier')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('fichier')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
/* $path = $request->file('fichier')->storeAs(public_path('contacts'), $fileNameToStore); */
$now = new \DateTime('now'); //Datetime
$monthNum = $now->format('m');
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F'); // Month
$year = $now->format('Y'); // Year
$monthYear = $monthName.$year;
Storage::disk('contacts')->putFileAs($monthYear, $request->file('fichier'), $fileNameToStore);
$path = Storage::disk('contacts')->url($monthYear.'/'.$fileNameToStore);
$contact->fichier = $path;
}
You can also have an idea of how can you create a folder using datetime elements (Month+Year) for my case.
Thanks.
I have a post with title, texts & image. But I can't save the image path to database. Here is my code.
public function save(Request $request, Post $post)
{
$this->validate(request(),
[
'title' => 'required',
'image' => 'image|mimes:jpg,png,jpeg'
]);
if($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($fileNameExt, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
Image::make($file)->resize(600, 600)->save( public_path('media/' . $fileNameToStore));
$post->image = $fileNameToStore;
auth()->user()->publish(
new Post(request(['title', 'text', 'image']))
);
}
return redirect ('/');
}
But it does not store image path to image column of database. Instead tmp data like C:\xampp\tmp\phpC549.tmp stored. What is wrong here?
I think you need to change the save code
auth()->user()->publish(
new Post(request(['title', 'text', 'image']))
);
to
auth()->user()->publish(
new Post([
'title'=>$request->title,
'text'=>$request->text,
])
);
since image val already set inside hasfile if condition
Sample Image path
public function addBlogCategoryPost(BlogCategoryRequest $request) {
$destinationPath = 'iamge path';
$data = [
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'seo_url' => $request->seo_url,
'meta_title' => $request->meta_title,
'meta_description' => $request->meta_description,
'meta_keywords' => $request->meta_keywords,
'meta_author' => $request->meta_author,
];
if ($request->hasFile('category_image')) {
$file = $request->file('category_image');
//move iamge to folder
$fileName = str_random(30) . '.' . $file->clientExtension();
$file->move($destinationPath, $fileName);
$data['category_image'] = $fileName;
}
$addTag = BlogCategory::create($data);
if ($addTag) {
return $addTag;
}
}
I am trying to upload files with Persian name like نام فایل but the file uploads and stores with unknown chars name like تقسیم_وظای٠it really stuck me I don't know what to do.
This is the controller code for uploading the file:
$files = Input::file('files');
$errors = "";
$file_data = array();
if(Input::hasFile('files'))
{
foreach($files as $file)
{
// validating each file.
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(
[
'file' => $file,
'extension' => Str::lower($file->getClientOriginalExtension())
],
[
'file' => 'required',
'extension' => 'required|in:jpg,jpeg,bmp,png,pdf,doc,docx,xls,xlsx,zip'
]
);
if($validator->passes())
{
// path is root/uploads
$destinationPath = 'uploads/docs/';
$filename = $file->getClientOriginalName();
$temp = explode(".", $filename);
$extension = end($temp);
$lastFileId = $object_id;
$lastFileId++;
$filename = $temp[0].'_'.$object_id.'.'.$extension;
$upload_success = $file->move($destinationPath, $filename);
if($upload_success)
{
$data = array(
'file_name' => $filename,
'meeting_id' => $object_id,
'user_id' => Auth::user()->id
);
//call the model function to insert the data into upload table.
meetingModel::uploadFiles($data);
}
else
{
// redirect back with errors.
return Redirect::back()->withErrors($validator);
}
}
else
{
// redirect back with errors.
return Redirect::back()->withErrors($validator);
}
}
}