I am trying upload file and filter by extension for save name in database by file type and I have a problem: enter image description here
My code example:
public function makepost(Request $req)
{
$req->validate([
'post' => 'required'
]);
$postbyid = Auth::user()->id;
$postby = Auth::user()->name . ' ' . Auth::user()->surname;
if ($req->hasFile('file')) {
$filename = 'WORLDREMO_' . date('YmdHis') . rand(0, 9999999) . '.' . $req->file->extension();
$req->file->move(public_path('files'), $filename);
$post = $req->post;
if ($req->file->extension() == 'mp4') {
$data = array('postbyid' => $postbyid, 'postby' => $postby, 'video' => $filename, 'post' => $post);
Posts::insert($data);
} else {
$data = array('postbyid' => $postbyid, 'postby' => $postby, 'image' => $filename, 'post' => $post);
Posts::insert($data);
}
} else {
$post = $req->post;
$data = array('postbyid' => $postbyid, 'postby' => $postby, 'post' => $post);
Posts::insert($data);
}
}
This is my code. I don't know what should I do now, because I'mm really confused in this problem.
in Controller for CSV Import
function import()
{
$this->load->library('csvreader');
$result = $this->csvreader->parse_file('./application/upload/financialloss.csv');
foreach($result as $value=>$key){
$date_report = date("Y-m-d H:i:s");
$handlingdate = $key['Handling Date'];
$handlingdate2 = strtotime($handlingdate);
$handlingdate3 = date('Y-m-d',$handlingdate2);
$nominal_awal = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $key['Transactions Nominal'])));
$nominal = str_replace(",","", $key['Transactions Nominal']);
$nominal1 = str_replace(".","", $nominal);
$nominal2 = str_replace("Rp","", $nominal1);
$tblfinancialloss = array(
'handlingdate' => $handlingdate3,
'lossdate' => $key['Loss Date'],
'ticketid' => $key['Ticket ID'],
'reporteremail' => $key['Reporter Email'],
'reporterusername' => $key['Reporter Username'],
'transactionsfraud' => $key['Transactions Fraud'],
'transactionsfinancialloss' => $key['Transactions Financial Loss'],
'transactionsnominal' => $nominal2,
'cityofuser' => $key['City of User'],
'provinceofuser' => $key['Province of User'],
'transactionscategory' => $key['Transactions Category'],
'casecategory' => $key['Case Category'],
'sourcedata' => $key['Source Data'],
'linkphisingmedia' => $key['Link Phising Media'],
'notesloss' => $key['Notes'],
'dateinput' => $date_report,
'inputby' => "by ".$this->session->userdata('name')
);
if(empty($key['Loss Date'])){
$this->session->set_flashdata('msg','TES1');
redirect(base_url()."index.php/DashboardFinancial/AddFinancialLoss");
}
else{
$this->Csv_Import_model->insert($tblfinancialloss);
$this->session->set_flashdata('msgs',' data, uploaded today !');
}
}
//unlink('./assets/data.csv');
}
And this is My Model for CSV Import
function insert($data)
{
$this->dbfinanciallossandsave= $this->load->database('financiallossandsave', TRUE);
$insert_query1 = $this->dbfinanciallossandsave->insert_string('tblfinancialloss', $data);
$insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query1);
$date = date("Y-m-d");
$this->dbfinanciallossandsave->where('handlingdate <=', $date);
//$this->dbfinanciallossandsave->where('lossdate <=', $date);
$this->dbfinanciallossandsave->query($insert_query);
}
And my model for where condition can't work. Can you help me?
Here i can only able preview the images on update the model. I want to load the images properly so user can remove one r more file and update will work accordingly Here is my controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
$session_data = \common\models\Customer::find()->where(['user_id' => $model->customer_user_id])->one();
$towing = \common\models\TowingRequest::find()->where(['id' => $model->towing_request_id])->one();
$images_old = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->all();
$images = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->one();
if (!$images) {
$images = new \common\models\Images();
}
if ($images_old) {
foreach ($images_old as $image) {
$baseurl = \Yii::$app->request->BaseUrl;
$image_url = $baseurl . '../backend/uploads/' . $image->thumbnail;
$all_images[] = Html::img("$image_url", ['class' => 'file-preview-image']);
}
} else {
$all_images = '';
}
$vehiclefeatures = new \common\models\VehicleFeatures();
$vehiclecondition = new \common\models\VehicleCondition();
$featuredata = \common\models\VehicleFeatures::find()->where(['=', 'vehicle_id', $model->id])->all();
$conditiondata = \common\models\VehicleCondition::find()->where(['=', 'vehicle_id', $model->id])->all();
$features = \common\models\Features::find()->all();
// $vf = Yii::$app->db->createCommand('SELECT * FROM features f left join vehicle_features vf on vf.features_id=f.id;')->queryAll();
$condition = \common\models\Condition::find()->all();
if ($model->load(Yii::$app->request->post()) && $towing->load(Yii::$app->request->post()) && $vehiclefeatures->load(Yii::$app->request->post()) && $vehiclecondition->load(Yii::$app->request->post()) && $images->load(Yii::$app->request->post())) {
$towing->save();
if (!$model->save()) {
$result = [];
// The code below comes from ActiveForm::validate(). We do not need to validate the model
// again, as it was already validated by save(). Just collect the messages.
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, $attribute)] = $errors;
}
return $this->asJson(['validation' => $result]);
// Yii::$app->response->statusCode = 422;
}
//delet vehicle features and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_features', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclefeatures->value) {
$vehicle_feature = \common\models\VehicleFeatures::inert_vehicle_feature($model, $vehiclefeatures->value);
}
//delete vehicle condition and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_condition', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclecondition->value) {
$vehicle_condition = \common\models\VehicleCondition::inert_vehicle_condition($model, $vehiclecondition->value);
}
$photo = UploadedFile::getInstances($images, 'name');
if ($photo) {
$command = Yii::$app->db->createCommand()
->delete('images', 'vehicle_id = ' . $model->id)
->execute();
$save_images = \common\models\Images::save_container_images($model->id, $photo);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'towing' => $towing,
'images' => $images,
'features' => $features,
'condition' => $condition,
'vehiclefeatures' => $vehiclefeatures,
'vehiclecondition' => $vehiclecondition,
'all_images' => $all_images,
'featuredata' => $featuredata,
'conditiondata' => $conditiondata,
'session_data' => $session_data,
]);
}
And here is my form where I have an issue on update the images. I know here I am just previewing the image by adding it in $all_images[] in the controller and initialPreview => $all_images in form to just show it on upload. Now I want exactly is to load the images properly so I can remove any image and can able to add more images. I just want here is how to load all the images properly in the upload widget on update After uploading it properly on update i can process it on the controller that i will delete and unlink all images and uploading the updating files
Here is my form with model images
<?=
$form->field($images, 'name[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*', 'multiple' => true],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
'showUpload' => true,
'initialPreview' => $all_images,
'overwriteInitial' => true,
],
]);
?>
Yii2 Fileinput Upload Multiple Images, AJAX based Images Previews and Delete Images.
Please Refer For Multiple Images : https://stackoverflow.com/a/53832224/2218492
Table : products_images
id (Primary)
product_id (FK)
image
Table : product
id (Primary)
Name
ect
Here View Forms...
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\widgets\FileInput;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo '<label class="control-label">Choose an Image file(.png, .jpg)</label>'; ?>
<?php
//For Update Form : Fetch Uploaded Images and create Array to preview
$imagesList = array();
$imagesListId = array();
foreach ($model->productsImages as $img) {
$imagesList[] = Url::base(TRUE) . '/' . $img->image;
$imagesListId[]['key'] = $img->id;
}
?>
<?php
$empty_image = Url::base(TRUE) . "/uploads/image-upload-empty.png";
echo FileInput::widget([
'model' => $model,
'attribute' => 'products_image[]',
'name' => 'products_image[]',
'options' => ['multiple' => true, 'accept' => 'image/*', 'id' => 'products_image_id'],
'pluginOptions' => [
'initialPreview' => $imagesList,
'initialPreviewConfig' => $imagesListId,
'deleteUrl' => Url::to(['products/delete-image']),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary col-lg-6 col-md-8 col-sm-8 col-xs-6',
'browseIcon' => '<i class="glyphicon glyphicon-plus-sign"></i> ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png'],
'previewFileType' => ['jpg', 'png'],
'initialPreviewAsData' => true,
'overwriteInitial' => false,
"uploadUrl" => Url::to(['products/upload']),
'uploadExtraData' => ['products_id' => $model->id, 'is_post' => $model->isNewRecord ? 'new' : 'update'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadThreshold' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadEnd' => Yii::t('app', 'Done'),
'msgFilesTooMany' => 'Maximum 15 products Images are allowed to be uploaded.',
'dropZoneClickTitle' => '',
"uploadAsync" => true,
"browseOnZoneClick" => true,
"dropZoneTitle" => '<img src=' . $empty_image . ' />',
'fileActionSettings' => [
'showZoom' => true,
'showRemove' => true,
'showUpload' => false,
],
'validateInitialCount' => true,
'maxFileCount' => 15,
'maxFileSize' => 5120, //5mb
'msgPlaceholder' => 'Select attachments',
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("upload");
}',
/* 'uploadExtraData' => 'function() {
var out = {}, key, i = 0;
$(".kv-input:visible").each(function() {
$el = $(this);
key = $el.hasClass("kv-new") ? "new_" + i : "init_" + i;
out[key] = $el.val();
i++;
});
return out;
}', */
'filepredelete' => 'function(event, files) {
//var abort = true;
var index = uploaded_images.indexOf(files);
if (index !== -1) uploaded_images.splice(index, 1);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
//return abort;
}',
'fileuploaded' => 'function(event, data, previewId, index){
//alert( data.response.initialPreviewConfig[0].key);
uploaded_images.push(data.response.initialPreviewConfig[0].key);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
}',
/* 'filepreupload' => 'function(event, data, previewId, index){
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log(data.jqXHR);
console.log("File pre upload triggered");
}', */
],
]);
?>
<?= $form->field($model, 'images_array')->hiddenInput()->label(false) ?>
<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
// initialize array
var uploaded_images = [];
JS;
$this->registerJs($script);
?>
Here Controller file:
<?php
/*
* Post products Images Upload Action Via FileInput Yii2 Extention.
*/
public function actionUpload() {
$files = array();
$allwoedFiles = ['jpg', 'png'];
if ($_POST['is_post'] == 'update') {
$products_id = $_POST['products_id'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'][0];
$fname = $_FILES['ProductsMaster']['name']['products_image'][0];
//Get the temp file path
$tmpFilePath = $tmpname;
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname;
$size = $_FILES['ProductsMaster']['size']['products_image'][0];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/' . $newFileName)) {
$productsImages = new productsImages();
$productsImages->products_id = $products_id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $newFileName;
$productsImages->created_at = time();
$productsImages->save();
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/' . $newFileName;
$files['initialPreviewAsData'] = true;
$files['initialPreviewConfig'][]['key'] = $productsImages->id;
return json_encode($files);
}
}
}
} /* else {
return json_encode(['error' => 'No files found for pload.']);
} */
return json_encode($files);
} else {
if (isset($_POST)) {
if ($_FILES) {
$files = ProductsMaster::SaveTempAttachments($_FILES);
return json_encode($files);
$result = ['files' => $files];
Yii::$app->response->format = trim(Response::FORMAT_JSON);
return $result;
} /* else {
echo json_encode(['error' => 'No files found for pload.']);
} */
}
}
}
/**
* Uploaded Images Delete Action on Update Forms Action
* #return boolean
*/
public function actionDeleteImage() {
$key = $_POST['key'];
if (is_numeric($key)) {
$products_image = ProductsImages::find()->where(['id' => $key])->one();
unlink(Yii::getAlias('#webroot') . '/' . $products_image->image);
$products_image->delete();
return true;
} else {
unlink(Yii::getAlias('#webroot') . '/uploads/products/temp/' . $key);
return true;
}
}
/**
** Create Products
**/
public function actionCreate() {
//Products Images
// temp store image moved and save to database.. with generated forms..
if (count($model->images_array) > 0) {
$images_array = explode(',', $model->images_array);
if (!empty($images_array) && $model->images_array != '') {
foreach ($images_array as $image) {
$file = Yii::$app->basePath . '/uploads/products/temp/' . $image;
$rename_file = Yii::$app->basePath . '/uploads/products/' . $image;
rename($file, $rename_file);
$productsImages = new productsImages();
$productsImages->products_id = $model->id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $image;
$productsImages->created_at = time();
$productsImages->save();
}
}
}
}
?>
Here Model
I added a load function to the attachment model.
<?php
/*
* Save Temp Images
*/
public static function SaveTempAttachments($attachments) {
$files = "";
$allwoedFiles = ['jpg', 'png'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'];
$fname = $_FILES['ProductsMaster']['name']['products_image'];
if (!empty($attachments)) {
if (count($fname) > 0) {
//Loop through each file
for ($i = 0; $i < count($fname); $i++) {
//Get the temp file path
$tmpFilePath = $tmpname[$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname[$i];
$size = $attachments['ProductsMaster']['size']['products_image'][$i];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/temp/' . $newFileName)) {
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/temp/' . $newFileName;
$files['initialPreviewAsData'] = true;
// $files['uploadExtraData'][]['is_post'] = 'new';
$files['initialPreviewConfig'][]['key'] = $newFileName;
}
}
}
}
}
}
}
return $files;
}
?>
Hi can someone know this i am beginner in Cakephp i tried to upload multiple images but it wont save.
Controller:
public function add() {
if ($this->request->is('post')) {
//$data = $this->request->getData();
if(!empty($_FILES['photo']['name'])){
$count = count($_FILES['photo']['name']);
for ($i=0; $i < $count; $i++) {
$filename = $_FILES['photo']['name'][$i];
$type = $_FILES['photo']['type'][$i];
$tmp = $_FILES['photo']['tmp_name'][$i];
$error = $_FILES['photo']['error'][$i];
$size = $_FILES['photo']['size'][$i];
$uploadPath = '../uploads/files/';
$file[$i]['user_id'] = $this->Auth->user('id');
$file[$i]['filename'] = $filename;
$file[$i]['file_location'] = $uploadPath;
$file[$i]['file_type'] = $type;
$file[$i]['file_size'] = $size;
$file[$i]['file_status'] = 'Active';
$file[$i]['created'] = date("Y-m-d H:i:s");
$file[$i]['modified'] = date("Y-m-d H:i:s");
}
$table = TableRegistry::get('files');
$entities = $table->newEntities($file);
if($table->saveMany($entities)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
but when i tried to debug all good but in saving it wont work! does my code has problem, can someone help me how to fix my add function
View:
echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']);
You are trying to save one record once using saveMany().
public function add()
{
if ($this->request->is('post')) {
$table = TableRegistry::get('files');
$uploadPath = '../uploads/files/';
if(!empty($_FILES['photo'])){
foreach ($_FILES['photo'] as $EachPhoto) {
$data[] = [
'user_id' => $this->Auth->user('id'),
'filename' => $EachPhoto['name'],
'file_location' => $uploadPath,
'file_type' => $EachPhoto['type'],
'file_size' => $EachPhoto['size'],
'file_status' => 'Active',
'created' => date("Y-m-d H:i:s")
];
}
$entities = $table->newEntities($data);
if($this->Files->saveMany($entitie)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error. I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
/** Function to Get Product **/
function get_product() {
$qry = mysql_query('SELECT * from product');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id" => $rows['id'],
"prod_name" => $rows['prod_name'],
"prod_desc" => $rows['prod_desc'],
"prod_price" => $rows['prod_price'],
"prod_quantity" => $rows['prod_quantity']
);
}
print_r(json_encode($data));
return json_encode($data);
}
what I tried and I get no data inserting
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";
$q = $conn->prepare($qry);
$q->execute(array(':prod_name'=>$prod_name,
':prod_desc'=>$prod_desc,
':prod_price'=>$prod_price,
':prod_quantity'=>$prod_quantity,
));
$qry_res = mssql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
db setup
<?php
/****** Database Details *********/
$host = "localhost";
$user = "root";
$pass = "";
$database = "shopping";
$con = mysql_connect($host,$user,$pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($database,$con);
/*******************************/
?>