Uploading files with infyom generator - laravel

I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}

This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>

Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}

Related

I want to use images of products that I register in the database - Laravel

I programmed a product registration. The registration for the database is working correctly. My problem is that I can't show the images that I registered in the database. I created an imput where the name of the image is inserted. This name is saved in the database and the image is saved with the same name, however it is saval in public. The images are inside the public / storage / products folder.
Controller:
public function index()
{
$products = Product::paginate(10);
return view('products.index', [
'products' => $products,
]);
}
public function store(Request $request)
{
// Create registration
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
// Image
if($request->file('imageProduct')->isValid()){
$nameFile = $request->imageName . '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
return redirect()->route('ProductControllerIndex');
}
}
view:
<div>
#foreach ($products as $product)
<p>
Id: {{ $product->id }}
</p>
<p>
Nome do produto: {{ $product->name }}
</p>
<p>
Preço: {{ $product->price }}
</p>
<p>
{{ $product->imageName }}
</p>
<p>
<img src="{{ asset('storage/products/'.$product->imageName) }}" alt="">
</p>
<hr>
#endforeach
</div>
The core issue here is that your Image's extension is not being saved to the database, so $product->imageName, when used in the asset() helper, doesn't generate a complete URL for the image. You'll need to refactor your code a little to get it to save:
public function store(Request $request) {
$nameFile = $request->input('imageName', '');
if($request->file('imageProduct')->isValid()){
$nameFile .= '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
}
$request->merge(['imageName' => $nameFile]);
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
return redirect()->route('ProductControllerIndex');
}
In the above code, the value for $nameFile is defaulted to the value in $request->input('imageName'), or an empty string '' if nothing is supplied. Next, if a valid image is uploaded, the $nameFile variable is appended with the extension. Lastly, the $request variable is updated with the name value for imageName. The remainder of the code creates the new Product with the data supplied (using the ->only() modifier) and redirect as required.
The rest of your code should be ok, as long as the file exists in the correct directory after ->storeAs() and the fully-qualified image name is saved to the database.
Note: If for whatever reason Product::create() doesn't work with this approach, you can use the new Product() ... $product->save() approach: (there might be an issue with $request->merge() using an existing key, as I can't actually test that)
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->imageName = $fileName;
$product->save();

Download file in laravel

I am new to Laravel and I trying to capture the filename stored on the database table called "Infrastructure" so that I can create a link for users to downloading that file. The download works but I always get the wrong file stored in the directory.
So in my controller called infrastructureController.php I have these codes.
public function show($id)
{
$infrastructure = $this->infrastructureRepository->find($id);
$Attachment = $infrastructure->inf_file; // captured filename in the database
if (empty($infrastructure)) {
Flash::error('Infrastructure not found');
return redirect(route('infrastructures.index'));
}
return view('infrastructures.show')->with('infrastructure', $infrastructure);
}
In my route or web.php
I have these codes...
Route::get('/download', function(){
$name = $Attachment;
$file = storage_path()."/app/public/infrastructure/".$Attachment;
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});
and finally, in my view file, I have this
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
Download Now
</div>
Can someone point out I did wrong here...
First you are not passing the name of the attachment from your View back to your controller so change your view to:
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
Download Now
</div>
Then in your route you need to access the name of the file like so:
Route::get('/download/{Attachment}', function($Attachment){
$name = $Attachment;
$file = Storage::disk('public')->get("infrastructure/".$Attachment);
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});

Laravel 5.8 image failed to upload

I cannot seem to upload an image file with Laravel. I keep getting the photo failed to upload.
My form:
<form id="save_report_form" action="{{ route('report.add') }}" method="post" enctype="multipart/form-data">
<input type="file" name="image" class="upload-photo" id="image" accept="image/png,image/jpg" />
</form>
My Controller:
public function add(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:png,jpg',
]);
// Get all file details and store in public
$disk = Storage::disk('public');
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = $file . '.' . $ext;
$disk->put($filename, file_get_contents($file), 'public');
return redirect()->back();
}
I have changed upload_max_filesize to 20mb for my dev server.
Where can I look to find the reason for the upload failure? I am not getting anything in the Laravel log. What have I missed. Thanks.
can you replace
$filename = $file . '.' . $ext;
with
$filename = $request->image->getClientOriginalName();
You can check what is the result of $filename with dd() /dd($filename) function and see if it is what you expect. If it is not, probably there is the problem.
Also as far as i see in the official docs(https://laravel.com/docs/5.8/filesystem#file-visibility) the usage of put() method is exampled without php native file_get_contents(check this also).

How to save file upload in local folder Laravel

I have button upload for uploading PDF in my view, the file was saved in database.
Here is my view html:
<div class="form-group">
{!! Form::label('file', 'File:') !!}
<p>{!! $attatchment->file !!}</p>
</div>
So I want to save it on my local folder, how to make its works ?
I'm using this: path="/file_storage";
$file = $request->file('avatar');
$destinationPath = 'file_storage/';
$originalFile = $file->getClientOriginalName();
$filename=strtotime(date('Y-m-d-H:isa')).$originalFile;
$file->move($destinationPath, $filename);
it will save the file in public/file_storage
<?php
$file = $request->file('photo');
$time = microtime('.') * 10000;
$filename = $time.'.'.strtolower( $file->getClientOriginalExtension() );
$destination = 'profile';
$file->move($destination, $filename);
?>

How to pass id to controller in laravel 5.2

I using this method to upload the image and passing the page id so i can store the path into database but having error "Missing argument 2 for App\Http\Controllers\RoundtablesController::postImage()"
This is my form
<div class="btn-group">
{!! Form::open(array('action' => 'RoundtablesController#postImage',$tables->id, 'files'=>true)) !!}
<div class="form-group">
{!! Form::label('Profile-Picture', 'Profile Picture:') !!}
{!! Form::file('profile_image',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
This is my route
Route::post('/roundtables/settings',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
This is my controller ,the $name should get the Page Id, but look like the id not passed to here yet
public function postImage(Request $request,$name){
$table_details =Detail::find($name);
//save image
if ($request->hasFile('profile_image')) {
//add new photo
$image = $request->file('profile_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldFilename = $table_details->profile_image;
//update database
$table_details->profile_image = $filename;
//Delete old image
Storage::delete($oldFilename);
}
$table_details->update();
Can i know where is the error? Sry i know this is very basic but i am new in laravel.
Route:
Route::post('/roundtables/settings/{id}',
['as' => 'roundtables.setting',
'middleware'=>['auth'],
'uses'=>'RoundtablesController#postImage']);
Action:
public function postImage(Request $request, $id) {
$Detail = Detail::findOrFail($id); // will return 404 or exception if record not found
if ($request->hasFile('profile_image')) {
$file = $request->file('profile_image');
$profile_image = time() . '.' . $file->getClientOriginalExtension();
$profile_image_file = public_path('images/' . $profile_image);
Image::make($image)
->resize(800, 400)
->save($profile_image_file);
$old_profile_image_file = public_path('images/'.$Detail->profile_image);
if(is_file($profile_image_file)) { // if new file successfully created
$Detail->profile_image = $profile_image; // changing profile_image
$Detail->save(); // saving
Storage::delete($old_profile_image_file);
}
}
}
in view open form like (use named route: roundtables.setting defined in router):
{!! Form::open(array('url' => route('roundtables.setting', $tables->id), 'files'=>true)) !!}
also it's a little bit strange $tables->id, are You sure that $tables is an instance of model (not an array or collection) ?
route should be like
Route::post('/roundtables/settings/{name}',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
Try this way...
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups#show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}

Resources