Geting the file object from a form in Symfony - php

I have a scenario where I have to make use of a form the old fashioned why like this;
<form action="{{ path('admin_app_address_import') }}" method="post" name="form_import">
<div class="form-group">
<label for="inputFile">File input</label>
<input type="file" id="inputFile" accept="text/csv" name="inputFile">
<p class="help-block">Select a CSV file to import.</p>
</div>
</form>
And then get the parameters from the form like this inside my action;
public function importAction(Request $request) {
$file = $request->files->get('inputFile');
var_dump($file);exit;
//...
}
But I keep on getting null. How can I get the file I try to read from? I don't need to store it in a database whatsoever, I just need to read the content to upload that to the database. I'm making a CSV import action, but I can't seem to get the file object.
When doing var_dump($request->request->all()); I do get the filename, but that won't work right?

When allowing file uploads, the encoding type of the form must be set to multipart/form-data:
<form ... enctype="multipart/form-data">

Related

How to insert random default image into database with Laravel?

I am developing a Laravel application.Its have a form which have image upload field and its also not a required field. Now i want to do if anyone submitting form without uploading image then a default random image will be inserted into database from public/images/default directory. How can i do that with Laravel? I have 10 images of that directory (ex: 1b.png, 2b.png, 3b.png....)
<form method="POST" action="{{ route($base_route.'.eventEdit', ['event_id' => $event->event_code]) }}" accept-charset="UTF-8" id="general_form" novalidate="novalidate">
<input name="name" type="text" value="something" class="name">
<input name="name" type="file" value="DefaultImageName" class="image">
<button class="btn btn-default"> Submit </button>
</form>
Add this code to your controller action
$images = scandir(public_path('images/default'));
$image = $request->file('DefaultImageName', $images[mt_rand(0, count($images -1))]);
I would't advise storing images in the database. The approach I take is usually, I store in the database a name, alias and path to the file.
You can do this depending on the pattern you're using on the application, but for your situation, what I'd do is create a mutator that validates whenever you're going to insert a record, if certain field is empty, it does something (if you're using eloquent I assume).
https://laravel.com/docs/5.2/eloquent-mutators
public function setImageAttribute($value)
{
if (empty($value)) {
$this->attributes['image'] = //fetch your image and apply your logic
} else { 
$this->attributes['image'] = value;
}
}
Otherwise, I'd create a formrequest that validates if a certain field is empty, I place some content in it (and this way, when it reaches the insertion code it already contains an image)
https://laravel.com/docs/5.2/validation

Update file via php

The form with the input element is below:
<?php
$post_new_file=$_FILES['post_new_file'];
if(isset($_POST['update'])){
if (!empty($post_new_file)) {
$post_file=$_FILES['post_new_file']['name'];
$post_file_temp=$_FILES['post_new_file']['tmp_name'];
move_uploaded_file($post_file_temp,"../pdf/$post_file");
}
$query="UPDATE posts SET post_file='{$post_file}' WHERE post_id='{$the_post_id}' ";
$create_post_query= mysqli_query($connect, $query);
confirmQuery($create_post_query);
?>
<form action="edit.php?source=<?php echo $the_post_id ?>" method="post" enctype="multipart/form-data">
<div class="form-group" style="border: solid #000 3px;">
<label for="post_file">Select New File</label>
<input type="file" name="post_new_file" >
</div>
</form>
I have problem when the $post_new_file exist. In this case when updating I lost the data in my db and the post can't have access into the file. In a few words I don't want changing the access of the file when I haven't insert a new file.
Thanks
you should check if $_FILES['post_new_file']['tmp_name'] is empty, the _FILES['post_new_file'] will exist even if there was an error with the file upload. you may even want to check the move upload worked as well to be extra sure you actually have the file, as the file could be uploaded but if the move fails you will lose the file as it was only stored temporarily

Form Posts Text Inputs But Not File

I am trying to submit file inside a form to Laravel backend. It posts all the other text fields but not file (when I dd($request->all()))
<form class="form-horizontal" role="form" method="POST" action="" enctype="multipart/form-data">
<input id="item_price" type="item_price" class="form-control" name="item_price" value="">
<!-- other inputs -->
<input type="file" id="product_image" name="product_image" onchange="previewImage(this);"/>
<img id="previewing" src="{{asset('noImage.gif')}}" style="width: 100%; height: 100%" />
</form>
item_price seems on dd($request->all()) and also other fields are seen, but no file input
When I display the image with jQuery (previewImage) before submitting the form, it shows the photo. But after I submit the form, on Laravel side it shows all the other fields and values but not any for file (when I use dd($request->all()).
On php.ini, max-post-size is 100M.
jQuery('#previewing').click(function() {
uploadImageClicked();
});
function uploadImageClicked() {
jQuery('#product_image').click();
}
dd($request->hasFile('product_image') returns false
In Laravel (which should be tagged in your question) it's not part of the Request class with the other form values, it's in the file method.
See https://laravel.com/docs/5.3/requests#retrieving-uploaded-files
$file = $request->file("image"); is what you're looking for.

How to save multiple values from input form fields to JS variable?

I am using plupload to upload image files. My goal is to save the name of the uploaded thumb_nail files to a session, in case user leaves page or an submit error happens.
Plupload creates file_names in this manner:
<div id="files">
<input type="hidden" id="p1adsfucka1h0p1s0624cauu623" name="files[]" value="p1adsfucka1h0p1s0624cauu623.jpg">
<input type="hidden" id="p1adsfucka1h0p1s0624cauu624" name="files[]" value="p1adsfucka1h0p1s0624cauu623.jpg">
</div>
from plupload functions I want to call this function:
function autosave_form_cl(session_name){
console.log($("input[name=files").val() + $('#title').val());
$.post("/act_autosave_formdata.php", {
session_name:session_name,
cellphone: $('#cellphone').val(),
files: $("input[name=files").val()
} );
}
This returns an undefined for the value of the file fields. How could I access and save those names? Submitting and saving the values to a session works by accessing $_POST.
Collect all [name=files] first then pass it to your $.post.
I assume what's inside <div id="files"> is all inputs with [name=files]
function autosave_form_cl(session_name){
//console.log($("input[name=files]").val() + $('#title').val());
files = [];
$('div#id').find('input').each(function(i,inp){
files.push($(inp).val());
});
console.log(files);
$.post("/act_autosave_formdata.php", {
session_name:session_name,
cellphone: $('#cellphone').val(),
files: files
} );
}
Let me know if it works.

Using PHPExcelReader to parse file and store values in array - File not found

I am using PHPExcelReader to parse an excel file (chosen by the user from their local machine). PHP will take those values and store them in an array and then reorganize it and display it on the screen in the form of a table.
However, after I browse for a file, once I click "Submit", I get the error: File not found
Here is the HTML:
<div class="row-fluid" style="margin-top:15px">
<h2>Step 1: Import the file</h2>
<p>Once uploaded, the window will display a preview of the document. Please check to make sure the column
headers match the data before uploading.</p>
<form action="../scripts/previewFile.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" />
<input type="submit" value="Preview File" name="submit">
<div id="filePreview" style="height: 500px; overflow: scroll;">
</div>
</form>
</div>
The previewFile.php file that is called:
function previewFile()
{
$filePath = $_FILES['file']['tmp_name'];
$excel = new Spreadsheet_Excel_Reader; // creates object instance of the class
$excel->read($filePath);
}
UPDATE
The error was a 404 for the PHP file "previewFile.php" that is called as an action.
Not sure what's wrong with my URL "../scripts/previewFile.php"
Here's my schema:
root
|_views
|_default
|_assets
|_scripts
|_previewFile.php
|_templates
|_step1.php <- the html file with the input tags
Your input name is fileToUpload, and you are looking in the $_FILES array for file, so it should be as follows:
function previewFile()
{
$filePath = $_FILES['fileToUpload']['tmp_name'];
$excel = new Spreadsheet_Excel_Reader; // creates object instance of the class
$excel->read($filePath);
}

Categories