Cannot upload file type image on Yii - yii

I has been successfully uploaded an image, but the file type of image is not uploaded. As Example 123.jpg, on the store folder of upload is only 123 (unknown file type).
Here is my code :
const URLX ="/../foto/";
public function actionCreate()
{
$model=new TbBatik;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['TbBatik']))
{
$model->attributes=$_POST['TbBatik'];
$simpanSementara=CUploadedFile::getInstance($model,'Foto');
if($model->save())
{
$simpanSementara->saveAs(yii::app()->basePath.self::URLX.$model->id_batik.'');
$this->redirect(array('view', 'id' => $model->id_batik));
}
}
$this->render('create',array(
'model'=>$model,
));
}
How to upload a file with originally file type with Yii?

You need to make a little change in your code:
$extension = $simpanSementara->getExtensionName();
$simpanSementara->saveAs(yii::app()->basePath.self::URLX.$model->id_batik.'.'.$extension);

Related

CKEditor 5 Image Upload Issues

I'm using ckeditor5 into my project. I have to support image upload so I have search and followed this stackoverflow article.
I have created an uploadAdapter which is:
class UploadAdapter {
constructor( loader, url, t ) {
this.loader = loader;
this.url = url;
this.t = t;
}
upload() {
return new Promise( ( resolve, reject ) => {
this._initRequest();
this._initListeners( resolve, reject );
this._sendRequest();
} );
}
abort() {
if ( this.xhr ) {
this.xhr.abort();
}
}
_initRequest() {
const xhr = this.xhr = new XMLHttpRequest();
xhr.open( 'POST', this.url, true );
xhr.responseType = 'json';
}
_initListeners( resolve, reject ) {
const xhr = this.xhr;
const loader = this.loader;
const t = this.t;
const genericError = t( 'Cannot upload file:' ) + ` ${ loader.file.name }.`;
xhr.addEventListener( 'error', () => reject( genericError ) );
xhr.addEventListener( 'abort', () => reject() );
xhr.addEventListener( 'load', () => {
const response = xhr.response;
if ( !response || !response.uploaded ) {
return reject( response && response.error && response.error.message ? response.error.message : genericError );
}
resolve( {
default: response.url
} );
} );
if ( xhr.upload ) {
xhr.upload.addEventListener( 'progress', evt => {
if ( evt.lengthComputable ) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
} );
}
}
_sendRequest() {
const data = new FormData();
data.append( 'upload', this.loader.file );
this.xhr.send( data );
}
}
import Plugin from '#ckeditor/ckeditor5-core/src/plugin';
import FileRepository from '#ckeditor/ckeditor5-upload/src/filerepository';
export default class GappUploadAdapter extends Plugin {
static get requires() {
return [ FileRepository ];
}
static get pluginName() {
return 'GappUploadAdapter';
}
init() {
const url = this.editor.config.get( 'gapp.uploadUrl' );
if ( !url ) {
return;
}
this.editor.plugins.get( FileRepository ).createUploadAdapter = loader => new UploadAdapter( loader, url, this.editor.t );
}
}
Now this is explained. I have 2 issues.
Once uploaded ( my upload on server is working fine and returning a valid url in format {default: url}, why is my image content inserted as data-uri and not in url as for easy image demo here. I want my image to be url like.
I would like to listen for a kind of success upload image ( with image id retrieved from upload server call ) to insert some content in my page. How to proceed ?
Thanks for help.
PS: I'm building ckeditor with command 'npm run build' from git repo cloned from https://github.com/ckeditor/ckeditor5-build-classic
EDIT:
Thanks to accepted response, I saw that I was wrong in returned data. I was not returning any URL in my uploader front end which was causing editor image to stay in img-data way. Once valid URL was returned, it was parsed automatically and my editor image was containing a valid url.
If the data-uri is still used after successful upload I would assume that server response was not processed correctly and the received url could not be retrieved. I have tested adapter code you provided and it works fine (with CKFinder on server side). I would check how the upload server response looks and if it can be correctly parsed.
When using CKFinder you will see:
and a parsed JSON response:
You could check if response is processed correctly in your adapter in:
xhr.addEventListener( 'load', () => {
const response = xhr.response;
...
}
Listening to successful image upload may be tricky as there is no event directly related to it. Depending on what exactly you are trying to achieve you may try to extend you custom loader so when successful response is received (and resolve() called) you may execute some code. However, in this state the image element is still not updated (in model, view and DOM) with new URL and UploadAdapter lacks a direct access to editor instance so it may be hard to do anything complex.
Better way may be to listen to model changes, the similar way it is done in ImageUploadEditing plugin (see code here) checking the image uploadStatus attribute change:
editor.model.document.on( 'change', () => {
const changes = doc.differ.getChanges();
for ( const entry of changes ) {
const uploaded = entry.type === 'attribute' && entry.attributeNewValue === 'complete' && entry.attributeOldValue === 'uploading';
console.log( entry );
}
} );
If it changes from uploading to complete it means the images was successfully uploaded:
You may also take a look at another answer, which shows how to hook into FileRepository API to track entire upload process - https://github.com/ckeditor/ckeditor5-image/issues/243#issuecomment-442393578.

Phalcon How to change template extension from phtml on html

I will want to change template extension from .phtml to .html, but my attempts has failed.
$this->view->registerEngines([
'html'
]);
You forgot the . before html file extension. Try like this:
// View
$di->setShared('view', function() use ($di) {
$view = new \Phalcon\Mvc\View();
$view->registerEngines([
'.yourextension' => function($view, $di) {
...
...
...
}
]);
return $view;
});
Just tested with .qq extension and it worked as intended.

Make an ajax request from a Prestashop module

I am making a module and I need to make an ajax request, with JSON response if possible, how can i do this ?
I don't understand really well the structure of Prestashop 1.7 on this.
Thanks !
This is pretty simple, you just have to make the controller with Prestashop's standards then link it to your frontend Javascript.
Name a php file like this : ./modules/modulename/controllers/front/ajax.php
Then put inside :
<?php
// Edit name and class according to your files, keep camelcase for class name.
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$module = new ModuleName;
// You may should do some security work here, like checking an hash from your module
if (Tools::isSubmit('action')) {
// Usefull vars derivated from getContext
$context = Context::getContext();
$cart = $context->cart;
$cookie = $context->cookie;
$customer = $context->customer;
$id_lang = $cookie->id_lang;
// Default response with translation from the module
$response = array('status' => false, "message" => $module->l('Nothing here.'));
switch (Tools::getValue('action')) {
case 'action_name':
// Edit default response and do some work here
$response = array('status' => true, "message" => $module->l('It works !'));
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
echo $json;
die;
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// Just put some vars in your template
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
?>
In your Module Hooks, you need to bring access to the route in JS, so we basicaly make a variable :
// In your module PHP
public function hookFooter($params)
{
// Create a link with the good path
$link = new Link;
$parameters = array("action" => "action_name");
$ajax_link = $link->getModuleLink('modulename','controller', $parameters);
Media::addJsDef(array(
"ajax_link" => $ajax_link
));
}
On the frontend side, you just call it like this in a JS file (with jQuery here) :
// ajax_link has been set in hookfooter, this is the best way to do it
$(document).ready(function(){
$.getJSON(ajax_link, {parameter1 : "value"}, function(data) {
if(typeof data.status !== "undefined") {
// Use your new datas here
console.log(data);
}
});
});
And voila, you have your ajax ready to use controller

Yii2 iterate dataprovider with relations

I need to know how to iterate through a Yii2 dataprovider with relations.
I have a model Asset that has a relationship to another model Make.
class Equipment extends \yii\db\ActiveRecord
{
// ...
public function getMake() {
return $this->hasOne(Make::className(), ['make_id' => 'make_id']);
}
}
In my controller, I have 2 functions, one to render a grid, and another to export the data to a CSV file.
public function actionEquipment()
{
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// Store the search model in session
Yii::$app->session->set('exportEquipmentModel', $searchModel);;
// Render grid
return $this->render('equipment', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionExportequipment()
{
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="equipment_report-' . date('YmdHi') .'.csv"');
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// Use the search model from session, or get all
if(\Yii::$app->session->get('exportEquipmentModel')) {
$searchModel = Yii::$app->session->get('exportEquipmentModel');
$dataProvider = $searchModel->search(false);
$dataProvider->setPagination(false);
}
// csv header
$columns =[
'serial_number',
'Make',
'Model',
];
echo implode(",", $columns) . " \r\n";
// csv data
foreach ($dataProvider->getModels() as $data) {
$row =[
$data['serial_number'],
// TODO: I need to resolve the relation here
$data['make_id'] // Works
// $data->make_id // Works
// $data->make->description // Does not work
// $data['make_id']['description'], // Does not work
$data['model_id']
];
echo implode(",", $row) . " \r\n";
}
}
As can be see from the comments in the code, various forms of getting the make->description field is not yielding results.
Lesson learned : Always check for errors.
My code was correct. However, the data was not what I expected. The dba deleted some of the makes and models after setting off foreign key checks. Therefore, $data->make.
I therefore changed the line
$data->make->description
to
!empty($data->make)?$data->make->description:'Not Set',

Blueimp jQuery File Upload - how to change upload directory

how can i change the upload directory?
i want to change the file upload directory dynamically
f.g : for each user,upload files to her/his folder
thanks
You can store the directory in a $_SESSION variable or in a $_COOKIE , and then get the saved value in the file /php/index.php
$uplDir = $_SESSION["uploadDirectory"].'/;
$option = array(
/* some options */
'upload_dir' => $uplDir,
/* .... */
);
$upload_handler = new UploadHandler($option);
ps. remember the session_start(); at the beginning
You can send that via parameters in the form data in js file
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
formData: [{ name: 'custom_dir', value: '/save/file/here/' }],
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
</script>
//=========================
while in the upload handler definition
require('UploadHandler.php');
$custom_dir = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['custom_dir'];
$upload_handler = new UploadHandler(array('upload_dir' => $custom_dir));