How to read file Laravel? - laravel

I load file using this:
public function fileUpload(Request $req)
{
$req->validate([
'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
]);
$fileModel = new File();
if ($req->file()) {
$fileName = time() . '_' . $req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = time() . '_' . $req->file->getClientOriginalName();
$fileModel->file_path = '/storage/' . $filePath;
$fileModel->save();
$this->read($fileModel->file_path);
return back()
->with('success', 'File has been uploaded.')
->with('file', $fileName);
}
}
Then I tried to read file after upload file:
public function read($path)
{
$file = FileStorage::get($path);
dd($file);
}
But I get this error:
File does not exist at path /storage/uploads/1654468183_test.csv.
How to specify path properly?

I would do this way:
if ($req->file()) {
$fileName = time() . '_' . $req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = $fileName; //<--set the right filename
$fileModel->file_path = '/storage/app/public/' . $filePath;
$fileModel->save();
$this->read($fileModel->file_path);
return back()
->with('success', 'File has been uploaded.')
->with('file', $fileName);
}

change this line
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
to this
$filePath = $req->file('file')->storeAs('uploads/', $fileName, 'public');

Related

upload an image through an api using in laravel

i have 2 web systems here,system a and system b.when i upload an image on system a i want as well send the image to system b.i am using an api to achieve the logic.am able to upload the image in system a perfectly but its unable be pushed to system b.am using guzzle http client to send the image to the api on upload.the upload on system a works very well but the data is being saved in system b.i have tested the api store function in postman and i get i 200ok status code but the data isnt being saved in the specific table in system b database.
here is my image save function in system a which works perfectly,it generates a folder which stores the image and a thumbnail folder inside the main folder where the thumbnail is stored.
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system b on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => $filename,
'contents' => file_get_contents( public_path() . "/images/product/$product_id/".$filename)
],
]
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = $e->getMessage();
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
here is my route for the api
Route::post(/push_productimage','APIController#savesystemAimage')->name(pushproductimage');
here is the api function in system b where the image and thumbnail should be recieved and stored to system b database
public function savesystemAimage(Request $request)
{
$productdetails=new Product;
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$filename = ('p' . sprintf("%010d", $productdetails->id)) . '-m' . rand(1000, 9999) . '.' . $extension;
$product_id = $productdetails->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail( public_path() . "/images/product/$product_id/" . $filename,
$dest,200);
$systemid = $request->product_id;
$productdetails->photo_1 = $filename;
$productdetails->thumbnail_1 = 'thumb_' . $filename;
$productdetails->save();
}
}
i dont know why the api function is not storing the data yet on postman it shows a 200ok status code but the image and thumbnail isnt saved.

RESOLVED Laravel 8 Update image and delete old image

I need help with a little thing.
I have a product table with an image:
Here is my function store which works perfectly
$fileName = null;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
Product::create([
'title' => $request->input('title'),
'subtitle' => $request->input('subtitle'),
'description' => $request->input('description'),
'price' => $request->input('price'),
'image' => $fileName,
]);
I am trying to modify the image in update but I do not know how to do it and I am in difficulty currently
Here is my update function where the image is missing to modify it and delete the old one
public function update(Request $request, Product $product)
{
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->save();
Thanks
You can modify your update function like this
public function update(Request $request, Product $product)
{
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage
if($fileName && $currentImage)
{
// Delete the old file i.e $fileName
}
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->image = $fileName;
$product->save();
}
It's good with this :
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage;
if($fileName && $currentImage)
{
Storage::delete('./img/' . $currentImage);
}
Thanks

how to add uniqid in image upload in laravel

I have a function to insert data in a table and this data includes image/file . I think my form didn't have problem but after I added this uniqid(), it can't be submitted with error "Call to a member function getClientOriginalExtension() on null"
public function store_pelatihan(Request $request)
{
$this->validate($request,[
// 'title' => 'required|min:5',
// 'description' => 'required|min:5|max:14'
] );
if($request->hasfile('file_scan'))
{
$file = $request->file('file_scan');
$name=$file->getClientOriginalName();
$extension = $request->image->getClientOriginalExtension();
$fileName = $file.'.'.uniqid().'.'.$extension;
$file->move(public_path().'/files/', $fileName);
$data = $fileName;
}
$users = new Master_seminar_pelatihan;
$users->user_id = $request->user_id ;
$users->nama_pelatihan = $request->nama_pelatihan ;
$users->nomor_pelatihan = $request->nomor_pelatihan ;
$users->tanggal = $request->tanggal ;
$users->uraian = $request->uraian ;
$users->tempat = $request->tempat ;
$users->file_scan = $data;
dd($data);
// $users->save();
// return redirect ('pelatihan')->with('success', 'Input Succes');
}
Previously, I was running this code and it was running without error:
$extension = $request->image->getClientOriginalExtension();
$fileName = $file.'.'.uniqid().'.'.$extension;
change this line :
$request->image->getClientOriginalExtension()
to :
$file->getClientOriginalExtension()
If you're concatenating with '.' before uniqid() it'll take extension so either you use '-' or '_'.
$fileName = $file.'_'.uniqid().'.'.$extension;
Or
$fileName = $file.'-'.uniqid().'.'.$extension;
Check file isValid() first
Get getClientOriginalExtension() of the $file (not $request->image)
Do not concatenate $file (it is UploadedFile) variable with strings. $name should be instead
if ($request->hasfile('file_scan') && $request->file('file_scan')->isValid()) {
$file = $request->file_scan;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . uniqid() . '.' . $extension;
$file->move(public_path() . '/files/', $fileName);
$data = $fileName;
}

laravel using switch cases to upload files

how can i upload inputs files in different folders i need to use switch cases to make every input file in different folder and did this code but when i execute it nothing happen i want know where problem
my view
{!! Form::file('file1', null,['class'=>'form-control']) !!}
{!! Form::file('file2', null,['class'=>'form-control']) !!}
{!! Form::file('file3', null,['class'=>'form-control']) !!}
{!! Form::file('file4', null,['class'=>'form-control']) !!}
my controler
$model = new Files($request->all());
switch ($model) {
case "file1":
if ($request->hasFile('file1')) {
$file = $request->file('file1');
$destinationPath = public_path() . '/file1';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file1'] = $filename;
$model -> file1 = $filename;
$model->save();
}
break;
case "file2":
if ($request->hasFile('file2')) {
$file = $request->file('file2');
$destinationPath = public_path() . '/file2';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file2'] = $filename;
$model->file2 = $filename;
$model->save();
}
break;
case "file3":
if ($request->hasFile('file3')) {
$file = $request->file('file3');
$destinationPath = public_path() . '/file3';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file3'] = $filename;
$model->file3 = $filename;
$model->save();
}
break;
case "file4":
if ($request->hasFile('file4')) {
$file = $request->file('file4');
$destinationPath = public_path() . '/file4';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$request['file4'] = $filename;
$model->file4 = $filename;
$model->save();
}
break;
}
Ummm yeah I had do something like that, but I do it use foreach loop and if after that.
And here's my sample code, I hope it can help :-D
$requests = $request->all();
$model = new File;
foreach ($requests as $key => $val) {
if ($key == 'file1' && !empty($val)) {
$destinationPath = public_path() . '/file1';
$filename = $val->getClientOriginalName();
$val->move($destinationPath, $filename);
$model -> file1 = $filename;
$model->save();
}
if ($key == 'file2' && !empty($val)) {
$destinationPath = public_path() . '/file2';
$filename = $val->getClientOriginalName();
$val->move($destinationPath, $filename);
$model -> file1 = $filename;
$model->save();
}
// And do it again as much as you need :D
}
Here you go, I hope it can help you pals :D

i m saving the multiple images at a single time with differnt ID in database in Laravel

and it is saved but the issue is all the images have different auto
increment ids in database i want to save the images with the same ids
which is save at the same time,kindly guide me.
****strong text** the code is below;**
$field = Input::file('image');
$location = public_path('uploads/');
foreach ($field as $k => $fd) {
$filename = str_random(2).'-' . time() . "." . $fd->getClientOriginalExtension();
$fd->move($location , $filename);
$product->image = $filename;
}
$user->save();
I think bellow code helps you..
You can try.
$picture = '';
if ($request->hasFile('image')) {
$files = $request->file('image');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}

Resources