Not able to get $_FILES in laravel 5 while file uploading - file-upload

I am currently working laravel 5 project. I am trying to do file upload but i found that i am not able to get $_FILES in my controller function. It shows only [] when i write dd($_FILES); in my controller function.
VIEW CODE:
{!!Form::open(['url'=>'admin','id'=>'MyUploadForm'])!!}
<input name="fileupload" id="fileupload" type="file" />
<input type="submit" id="submit-btn">
{!!Form::close()!!}
ROUTE CODE:
Route::get('admin', 'CouponcodefileController#index');
Route::post('admin', 'CouponcodefileController#uploadfile');
CONTROLLER FUNCTION:
public function uploadfile() {
dd($_FILES);
}
Please guide in this. Thanks.

Try:
"files" => true
View
{!!Form::open(['url'=>'admin','id'=>'MyUploadForm', 'method'=>'POST', 'files'=>true])!!}
<input name="fileupload" id="fileupload" type="file" />
<input type="submit" id="submit-btn">
{!!Form::close()!!}
Controller
public function uploadfile() {
$file = \Input::file('fileupload'));
// $file = \Request::file('fileupload'));
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
dd($file);
}
http://api.symfony.com/2.6/Symfony/Component/HttpFoundation/File/UploadedFile.html

Do it the Laravel way (5.1):
CONTROLLER FUNCTION:
public function uploadfile(Request $request) {
// Laravel 5.0: $file = Request::file('fileupload');
$file = $request->file('fileupload');
dd($file);
}
https://laravel.com/docs/5.1/requests#files

Related

Uploading asp.net core 3.1 Razor

I'm trying to upload files in ASP.NET core 3.1, but in my Post I'm not receiving the file.
That count = 0 is what I always get.
#cshtml
<input asp-for="app.FormFile" id="input-2" name="input2[]" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
#cshtml.cs
public async Task<IActionResult> OnPostAsync(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = Path.GetTempFileName();
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
}
}
// Process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size });
}
In ASP.NET core 2.0 this worked fine! What's wrong?
The param name is files, but you're explicitly setting the input name to input2[], so they don't match up. ASP.NET Core isn't going to try to interpret that you've uploaded some files so you probably want them to go on this param. If it can't find something to bind the data to (by name), it's just going to discard it and move on.
The name should files so it matches up to the param name: name="files".
even if I pass the name it still came with count = 0 <input asp-for="Laudos.FormFile" id="files" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
You can try to specify an encoding type (enctype) of multipart/form-data for your <form> tag, like below.
<form method="post" enctype="multipart/form-data">
<input asp-for="Laudos.FormFile" id="input-2" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
<input type="submit">
</form>
Test Result

passing data via redirect laravel 5

I have some problems when passing data via redirect in laravel 5, i get some samples code.. here my code
controller
if($validator->fails()){
return redirect()->back()->withErrors($validator->errors())->withInput();
}else{
if (Hash::check($request->old_password, $employee->password)){
$user = [
'username' => $input['username'],
'password' => Hash::make($input['password']),
];
$employee->fill($user)->save();
return redirect('/employees');
}else{
dd('test');
$error = 'Your old password is incorrect';
return redirect()->back()->with('error',$error);
}
}
view
<div class="form-group">
<label for="old_password" class="col-sm-2 control-label">Password Lama</label>
<div class="col-sm-5">
<input type="password" class="form-control" name="old_password" placeholder="Password Lama" required />{{ $errors->first('old_password') }}{{ $error = session('error') }}
</div>
</div>
there is no error message, but $error cannot display my messages.. anyone can help me?
thanks a lot...
}else{
dd('test');
$error = 'Your old password is incorrect';
return redirect()->back()->with('error',$error);
}
with dd('test'), you are exiting the application before a value was stored in session. remove that and let redirect.
and secondly, while dealing with session, do not use dd(). it may create undesirable result as session is a terminable middleware.
The DD command returns info to the browser and then stops executing code. Try commented this out.

Google Script for Uploading File Not Working

I wrote a script for uploading files to my Google Drive using the Google Script. I deployed it as a WebApp but it's not working and I don't know why. The button just gets stuck on "Subiendo..." and never changes anything inside my Drive. I'm sure I gave the script all the permissions and I already tried to see what's happening on my own without any sucess. Can you maybe help me find what should I do? I post the code here:
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('main').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function serverFunc(theForm) {
try{
var folder_name = "publicaciones";
var folder,folders = DriveApp.getFoldersByName(folder_name);
if(folders.hasNext()){
folder = folders.next();
}else{
folder = DriveApp.createFolder(folder_name);
}
Logger.log("TheForm", theForm == null);
var blob = theForm.theFile;
Logger.log("Blob!", blob == null);
var file = folder.createFile(blob);
Logger.log("File:", file.getName());
return "Archivo subido exitosamente: " + file.getUrl();
} catch(error){
Logger.log("error: ", error.toString());
return error.toString();
}
}
** main.html **
<div>
<form id="myForm">
<input type="file" name="theFile">
<input type="hidden" name="anExample">
<br>
<input type="button" value="Subir Archivo" onclick="this.value='Subiendo...';
google.script.run.withSuccessHandler(fileUploaded).serverFunc(this.parentNode);
return false;">
</form>
</div>
<div id="output">
</div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
I'd appreaciate any help or pointers you can give me. Thanks a lot!
Looks like there is a bug currently that Google is working on. I found a possible fix:
Change your input tag to this:
<input type="button" value="Subir Archivo" onclick="callServerCode()"/>
Add a function to the <script> tag:
<script>
function callServerCode() {
var formToSend = document.getElementById('myForm');
google.script.run
.withSuccessHandler(fileUploaded)
.serverFunc(formToSend);
};
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
Note that inside the new function, it gets the form using var formToSend = document.getElementById('myForm');
And change IFRAME to NATIVE.
It's a doc issue needs to fix with Google when using SandBoxMode=IFRAME currently. See here. I've tested it works by swapping IFRAME to NATIVE. You can simply do it:
function doGet() {
return HtmlService.createHtmlOutputFromFile('main');
}
Google has turned of NATIVE for SandBoxMode. It is now set to IFRAME only.
See here

how to add input value from session using ajaxlink in yii

I am kind of lost on how to do this in my view.
I want to add the quantity. Right now, it adds but how do I get the input value into my ajaxlink?
My controller is using session to add.
<input id="quantity" type="text" value="1" class="span1">
<div id="cart-text">
<?php echo CHtml::ajaxLink(' Add ',
Yii::app()->createUrl('controller/basketAjax',array('id'=>$_GET['id'])),
array('success'=>'function(data){...
controller:
$session=new CHttpSession;
$session->open();
if (!isset(Yii::app()->session['cart']))
{
$quantity = 1;
$session->add('cart',array(
'product_id.'.$id=>array("id"=>$id,
'quantity'=>$quantity)
));
}
else
{
$cart = Yii::app()->session['cart'];
$array = $cart['product_id.'.$id];
if (isset($array)){
$array['quantity']=$array['quantity']+1;
} else {
$t = array('product_id.'.$id=>array("id"=>$id,'quantity'=>$quantity));
array_push($cart,$t);
}
$session->add('cart', $products);
}
you can do this by using keyup function of jquery. First set the id of link as "mylink". Compute the url by using createUrl.
<script type="text/javascript" >
$("#quantity").keyup(function(){
var url=<?php echo Yii::app()->createUrl('controller/basketAjax') ?>;
$("#mylink").attr("href","");
$("mylink").attr("href",url +$(this).val());
});
</script>
Now i explain whats happening above. first i catch the event keyup on input you are using. It will be called each time you press a key on input. Now url=<?php echo Yii::app()->createUrl('controller/basketAjax') ?>; this code is returning you the base url to your action without any parameters being passed.this line $("#mylink").attr("href",""); will set the href of your link to " "( means nothing). Now this line $("mylink").attr("href",url +$(this).val()); is appending the value of the input you are getting from the input.
Remember you have to put the separator in between like
$("mylink").attr("href",url+"/" +"id"+"/"+$(this).val());
Above i have assumed that the href in your case looks like "projectname/index.php/controller/action/id/something". Thats y i have used separators in between but you can customize it according to your needs.
ajaxLink will not work (from what I know), just build it the old fashion way with jquery. Your best solution is actually to put it in a form and submit the form. Something like
<?php
Yii::app()->clientScript->registerCoreScript('yiiactiveform');
$form=$this->beginWidget('CActiveForm', array('action'=>Yii::app()->createUrl('cart/addProduct')));?>
<input type="text" name="quantity" value="1">
<input type="hidden" name="Product_id" value="<?php echo $model->id;?>">
<?php echo CHtml::ajaxSubmitButton('Save',CHtml::normalizeUrl(array('cart/addProduct','render'=>true)),
array(
'dataType'=>'json',
'type'=>'post',
'success'=>'function(data) {
if(data.status=="success"){
$("#formResult").html("form submitted successfully.");
}
else{
$.each(data, function(key, val) {
$("#user-form #"+key+"_em_").text(val);
$("#user-form #"+key+"_em_").show();
});
}
}',
)); ?>
<?php $this->endWidget(); ?><!-- .contact -->
Sorry for the indenting, hard to indent properly here.

MonoRail File Upload

I don't suppose anyone's clued up on this? The documentation is terrible and far outdated (the best resource I could find was dated 2006).
My form:
<form action="DoCreate.rails" method="post">
${FormHelper.LabelFor("master.Name", "Name", {"class":"label"})}
${FormHelper.TextField("master.Name", {"class":"text-input full-width"})}
${FormHelper.LabelFor("masterFile", "File", {"class":"label"})}
<input type="file" id="masterFile" name="masterFile" />
<div class="edit-controls">Back | <input type="submit" value="Create" /></div>
</form>
My controller action:
public void DoCreate(Master master, HttpPostedFile masterFile)
{
try
{
Bus.Master.Create(master);
if (masterFile != null)
{
masterFile.SaveAs(#"C:\" + masterFile.FileName);
}
RedirectToAction("Index");
}
catch (ApplicationException e)
{
PropertyBag["error"] = e.Message + "<br />" + e.StackTrace;
Create();
RenderView("Create");
}
}
I followed this guide also with no avail as it doesn't tell you what to do on the actual HTML page.
Looks like the problem is with the declaration of the form.
When uploading files, you should use add another attribute to the form element: enctype="multipart/form-data"