CLI stopped working error - laravel-5

I get "CLI stopped working" error when i press the upload button.I used the sample code from one of the website to upload file into the database column. I use Laravel 5.2.39. command used: php artisan serve
Code:(Only test version)
Form.blade.php
<form method="post" enctype="multipart/form-data" action="/upload_file">
{{ csrf_field() }}
<input type="file" name="file" />
<input type="submit" name="submit" value="upload" />
</form>
Routes.php
(Not an ideal place to code this but it is only for file upload test purpose)
Route::get('/upload_form', function()
{
$data['files'] = Attachment::get();
return View::make('form', $data);
});
Route::post('/upload_file', function()
{
$rules = array(
'file' => 'required|mimes:doc,docx,pdf',
);
$validator = Validator::make(Request::all(), $rules);
if(Request::hasFile('file'))
{
$f = Request::file('file');
$att = new Attachment;
$att->name = $f->getClientOriginalName();
$att->file = base64_encode(file_get_contents($f->getRealPath()));
$att->mime = $f->getMimeType();
$att->size = $f->getSize();
$att->save();
return Redirect::to('/upload_form');
}
});
Has anyone encountered this issue? Need help.

Related

Failing to upload file in laravel

Am having the form which I want to upload file but i got null on the fileUpload field when I submit to the controller
here is my Form
<form action="{{route('manager.expense.store')}}" method="POST" id="manager_add_new_expense" enctype="multipart/form-data">
enter code here
<div class="mb-3">
<label for="example-input-palaceholder">Add Supporting Document</label><small class="ml-auto align-self-end"><b>
Doc Such as: Receipt, Mpawe, Orders, Etc ...</b></small>
<input type="file" class="form-control #error('Uploadfile') is-invalid #enderror" id="Uploadfile" name="Uploadfile" value="">
Also my controller content bellow
//
$user = User::findOrFail(Auth::id());
$validator = Validator::make($request->all(), [
'Uploadfile' => 'required|mimes:doc,docx,pdf,txt,png,jpg|max:500000'
]);
if ($validator->fails()){
// return back()->withErrors($validator)->withInput();
return response()->json(["error"=>true, "message"=>$validator->errors()->first()]);
}
$filename = $request->file('Uploadfile');
$filen = date('YmdHis')."-".$filename->getClientOriginalName();
$request->file('Uploadfile')->move(storage_path('expensefile'), $filen);
I don't know why I am getting the Null value, only Am failing on the the validation like I have no file found.
try adding #csrf and make sure your route is a post route
I have found that the Error was i was submitting the form using AJAX yet there was no code to enable the upload
Just I added this and it works
data: new FormData(this),
contentType: false,
cache: false,
processData:false,

File does not exist (ncjoes/office-converter, laravel)

i was using ncjoes/office-converter, trying to upload .docx and convert it to .pdf, but it occurred error when it converts to .pdf
the error shows NcJoes\OfficeConverter\OfficeConverterException
File does not exist --test.docx
view
<form action="/notes" method="POST" role="form" enctype="multipart/form-data">
#csrf
#method('POST')
<div>
<label for="title">title:</label>
<input id="title" name="title">
</div>
<div>
<label for="topdf">upload:</label>
<input type="file" id="topdf" name="topdf">
</div>
<button type="submit" class="btn-sm btn-primary">add</button>
</form>
controller
public function store(Request $request)
{
$validatedData = $request->validate([
'topdf' => 'required|mimes:docx',
'title'=>'required'
]);
$Name = str_replace(" ","",$request->input('title'));
$FileName = $Name . '.' . $request->topdf->extension();
$request->topdf->move(public_path('pdf'), $FileName);
$converter = new OfficeConverter($FileName);
//$fin=$converter->convertTo('output-file.pdf');
//$fin->move(public_path('pdf'), $FileName);
}
i think $converter = new OfficeConverter($FileName); was wrong, but idk how to fix ;;
First upload the file this way:
$file = $request->file('topdf')->store('pdf');
$path = Storage::path($file);
And then, try to access the file and convert via the $path variable:
$converter = new OfficeConverter($path);

Input type submit won't trigger when it's clicked

I have trouble with my code, I want to create an upload button to upload my .xlsx file, but it won't trigger even when I try to click it.
My view.php :
<form action="<?php echo base_url("index.php/fin/cost_control/workingcanvas/import"); ?>" method="post" id="import_form" enctype="multipart/form-data">
<p><label>Pilih File Excel</label>
<input type="file" name="file" id="file" required accept=".xls, .xlsx" /></p>
<br />
<input type="submit" id="import" name="import" value="Import" class="btn btn-info" />
</form>
My controller:
public function import(){
include APPPATH.'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader->load('excel/'.$this->filename.'.xlsx');
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true);
$numrow = 1;
foreach($sheet as $row){
if($numrow > 1){
array_push($data, array(
'nis'=>$row['A'],
'nama'=>$row['B'],
'jenis_kelamin'=>$row['C'],
'alamat'=>$row['D'],
));
}
$numrow++;
}
$this->SiswaModel->insert_multiple($data);
redirect("Siswa");
}
and my model:
public function insert_multiple($data){
$this->db->insert_batch('siswa', $data);
}
I've tried with adding some part on autoload such as
$autoload['helper'] = array('url','form','file');
Any suggestions or advice? Thanks.
first load form helper in autoload file of codeigniter or load manually
$autoload['helper'] = array('url'); // autoload
$this->load->helper->('form'); // manually loading form helper
you better use this
$attributes = array('enctype' => 'multipart/form-data');
echo form_open('index.php/fin/cost_control/workingcanvas/import', $attributes);
<your upload form code>
<?php echo form_close(); ?>
instead of tags
more info: https://codeigniter.com/user_guide/helpers/form_helper.html

How to fix AJAX modal form in Laravel 5.3

I've upgraded my app from Laravel 4.2 to Laravel 5.3. On an index page listing citations, I have an AJAX modal form to edit or view the login credentials for the citation. This was working fine in Laravel 4.2, but I cannot for the life of me get it to work in 5.3. After about 5 hours Googling and trying different things, I thought I would post it here so that someone way more experienced than me can point me in the right direction.
Here's the link on the index page:
<a style="cursor: pointer; " title= "Login Credentials" data-loopback="cit-pg-1" data-citationid="1079" class="getCitationdetails"><span class="glyphicon glyphicon-lock " title="Login Credentials"></span></a>
And here's the JavaScript:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error:function(){
alert('Error');
}
})
})
Here's my route:
Route::match(['get', 'post'], '/citation-password', 'CitationsController#citationpassword');
And here's the Controller method that generates the form on get and saves the data on post:
public function citationpassword()
{
if (Request::ajax()) {
$data = Request::all();
if (!$data['citationid']) {
return redirect('/citations')
->with('flash-danger', 'Missing citation id for Login credentials form!!');
}
// Save loopback variable if we have it in order to return user to the page where they came from; default return location is citations
$loopback = 'citations';
if (array_key_exists("loopback", $data)) {
$loopback = $data['loopback'];
}
$getcitationdetails = Citation::where('id', $data['citationid'])->select('id', 'site_id', 'username', 'password', 'login_email', 'login_notes')->first();
$getcitationdetails = json_decode(json_encode($getcitationdetails), true);
$getsitedetails = Site::where('id', $getcitationdetails['site_id'])->select(
'id',
'directory_username',
'directory_password',
'security_questions',
'email_account',
'email_account_password',
'email_account_name',
'google_user',
'google_pwd',
'name_of_google_account'
)->first();
$getsitedetails = json_decode(json_encode($getsitedetails), true);
$response ="";
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
if (!empty($getsitedetails['directory_username'])) {
$response .= '<div class="form-group">
<label for="recipient-name" class="col-form-label">Default login credentials for this site:</label>
<p>Username: '.$getsitedetails['directory_username'].'
<br />Password: '.$getsitedetails['directory_password'].'
<br />Email account: '.$getsitedetails['email_account'].'
<br />Email password: '.$getsitedetails['email_account_password'].'
<br />Name on email account: '.$getsitedetails['email_account_name'].'
<br />Default security questions: '.$getsitedetails['security_questions'].'</p>
<p>Gmail account: '.$getsitedetails['google_user'].'
<br />Gmail password: '.$getsitedetails['google_pwd'].'
<br />Name on Gmail account: '.$getsitedetails['name_of_google_account'].'</p>
</div>';
}
$response .= '
<input type="hidden" name="_token" value="'.csrf_token() .'" />
<input type="hidden" name="citation_id" value="'.$data['citationid'].'" />
<input type="hidden" name="loopback" value="'.$loopback.'" />
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" class="form-control" name="username" value="'.$getcitationdetails['username'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="text" class="form-control" name="password" value="'.$getcitationdetails['password'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login email used:</label>
<input type="text" class="form-control" name="login_email" value="'.$getcitationdetails['login_email'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login notes:</label>
<textarea class="form-control" style="height:130px;" name="login_notes">'.$getcitationdetails['login_notes'].'</textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="success">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</form>';
return $response;
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
In an effort to isolate the error, I even simplified the form in the controller like this:
public function citationpassword()
{
if (Request::ajax()) {
return '<p>This is the modal form!</p>';
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
and also simplified the route to this:
Route::get('/citation-password', 'CitationsController#citationpassword');
but all I get when I click the link is a popup notice, "Error."
I'm not experienced with AJAX. How do I get the form to display in Laravel 5.3?
And/or, how can I change the JavaScript function so that it shows the actual error instead of the "Error" notice? (I tried a number of methods I found on StackOverflow to display errors but all of them resulted in NO error notice; just a blank page. And, I've not been successful at getting my Firefox debugger to show the errors either.)
Thanks!
The correct way to debug the JavaScript is to post the errors this way:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
})
})
Once you do so, you will see that the error has to do with missing CsrfToken for the form. [The actual error message is from the Laravel framework: Illuminate\Session\TokenMismatchException: in file /home/reviewsites/moxy53/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php on line 6] Since both the get and post verbs use the same route, Laravel is requiring the CsrfToken before the form with the Csrf field gets generated.
It is possible (but NOT recommended!) to exclude this route from CSRF protection by editing App\Http\Middleware\VerifyCsrfToken.php with the following exception:
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'/citation-password',
];
However, a much better approach is to add the token. It is correct that since you are using a post method to send the data values to the controller, you cannot use the controller to generate the token field in the form. Hence, the solution is to take the html out of the controller and put it in the blade. These lines:
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
...
</div>
</form>';
should not be in the $response generated by the controller, but should instead be in the modal div in the blade itself. THEN, you can add the CSRF field in the blade thus:
<form action="{{url('/citation-password')}}" method="post">
{{ csrf_field() }}
<div class="modal-body" id="AppendLoginDetails">
</div>
</form>

Laravel, upload image errors

I know, that there are many many cases about this theme already, but I looked them through, and could not find desired. Also I noticed that not a lot of the users got their answer.
I am working with Laravel5, and I'm trying to upload a picture. Simple upload, just save any picture in public/img folder.
I have looked up some tutorials and came up with this code:
View form:
<form action="{{URL::to('adminPanel/addImg/done/'.$projectId)}}" method="get" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And the controller code:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$filename = $id;
$file->move($destinationPath);
}
I keep getting this error :
Call to a member function move() on a non-object
And I am sure, that the chosen file is image.
I would appreciate any help
So its done, the main issue was the POST part! Also the file format, but here are the correct code, that adds the image:
form:
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}"> //this part is to make POST method work
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
controller:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$file->move($destinationPath, $id.'.png');
}
I don't know if you are using Laravel 4.2 or 5.0. But..
I recommend you to use illuminate/html - Form class. Try to use POST instead GET to upload files (https://stackoverflow.com/a/15210810/781251, http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 , http://php.net/manual/en/features.file-upload.post-method.php , http://php.net/manual/en/features.file-upload.php)
If Laravel 4.2:
View:
{{ Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) }}
<label for="file">File</label>
{{ Form::file('file') }}
{{ Form::close() }}
Controller:
public function postImage()
{
if( ( $file = Input::file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return Redirect::back();
}
throw new \Exception('Error while upload file');
}
Laravel 5.0
View:
{!! Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) !!}
<label for="file">File</label>
{!! Form::file('file') !!}
{!! Form::close() !!}
Controller:
public function upload(Request $request)
{
if( ( $file = $request->file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return redirect()->back();
}
throw new \Exception('Error while upload file');
}
To create a file with a new name and keep the extension:
$ext = $file->getClientOriginalExtension();
$newName = str_random(20) . '.' . $ext;
$file->move( storage_path('images') , $newName );
Now, you have a new name with the same extension. To validate if your file is an image or..whatever, use Validator.
Try this
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And get the image as
public function postImage(Request $request) {
$image = $request->file("image");

Resources