J’ai réussi à coder l’upload d’une image pour modifier l’icône d’un périphérique. Le code est probablement encore à nettoyer car je suis parti du code présent dans le core Jeedom.
Les images sont uploadées dans /plugins/plugin_name/data.
Redéfinir
$pluginName = 'wifilightV2';
plugins/plugin_name/core/ajax/plugin_name.ajax.php :
try {
require_once dirname(__FILE__) . '/../../../../core/php/core.inc.php';
include_file('core', 'authentification', 'php');
if (!isConnect('admin')) {
throw new Exception('401 Unauthorized');
}
ajax::init(array('uploadCustomImg'));
if (init('action') == 'uploadCustomImg') {
$path = init('filepath');
if (!isset($_FILES['file'])) {
throw new Exception(__('Aucun fichier trouvé. Vérifiez le paramètre PHP (post size limit)', __FILE__));
}
$extension = strtolower(strrchr($_FILES['file']['name'], '.'));
if (!in_array($extension, array('.jpg', '.png'))) {
throw new Exception('Extension du fichier '.$extension.' non valide (autorisés : .jpg .png)');
}
if (filesize($_FILES['file']['tmp_name']) > 100000) {
throw new Exception(__('Le fichier est trop lourd (maximum 100 ko)', __FILE__));
}
$filepath= __DIR__ . "/../../../../".$path.$_FILES['file']['name'];
if(file_exists($filepath)){
throw new \Exception(__('Une image du même nom existe déjà : la supprimer d\'abord',__FILE__));
}
file_put_contents($filepath,file_get_contents($_FILES['file']['tmp_name']));
if(!file_exists($filepath)){
throw new \Exception(__('Impossible de sauvegarder l\'image',__FILE__));
}
ajax::success(true);
}
throw new Exception(__('Aucune méthode correspondante à : ', __FILE__) . init('action'));
/* * *********Catch exeption*************** */
} catch (Exception $e) {
ajax::error(displayExeption($e), $e->getCode());
}
plugins/plugin_name/desktop/php/plugin_name.php :
<?php
if (!isConnect('admin')) {
throw new Exception('401 - Accès non autorisé');
}
$pluginName = 'wifilightV2';
$plugin = plugin::byId($pluginName);
sendVarToJS([
'eqType' => $plugin->getId(),
'pluginName' => init('pluginName', $pluginName),
]);
?>
<div class="form-group image">
<label class="col-md-4 control-label help" data-help="{{Nom de l'image alternative de l'équipement. Laisser vide s'il n'y a pas d'image alternative. Si l'image n'est pas accessible, l'image par défaut sera affichée.}}">{{Nom du fichier image alternative :}}</label>
<div id="div_templateTest" class="col-md-6 input-group">
<input type="text" class="eqLogicAttr form-control imgMod form-control input-sm roundedLeft" data-l1key="configuration" data-l2key="image" placeholder="{{MonImage.png ou laisser vide}}"/>
<span class="input-group-btn">
<a class="btn btn-sm chooseImage roundedRight" ><i class="fas fa-plus-circle"></i> {{choisir}}</a>
</span>
</div>
</div>
<?php include_file('desktop', 'uploadFile', 'js', $pluginName); ?>
plugins/plugin_name/desktop/js/uploadFile.php :
function chooseImage(_callback, _params) {
if ($("#mod_selectIcon").length == 0) {
$('#div_pageContainer').append('<div id="mod_selectIcon"></div>')
$("#mod_selectIcon").dialog({
title: '{{Choisissez une image}}',
closeText: '',
autoOpen: false,
modal: true,
height: (jQuery(window).height() - 150),
width: 1500,
open: function() {
if ((jQuery(window).width() - 50) < 1500) {
$('#mod_selectIcon').dialog({width: jQuery(window).width() - 50})
}
$('body').css({overflow: 'hidden'});
setTimeout(function() {initTooltips($("#mod_selectIcon"))},500)
},
beforeClose: function(event, ui) {
$('body').css({overflow: 'inherit'})
}
});
}
var url = 'index.php?v=d&plugin='+pluginName+'&modal=modal.uploadImage'
$('#mod_selectIcon').empty().load(url,function() {
$("#mod_selectIcon").dialog('option', 'buttons', {
"Annuler": function() {
$(this).dialog("close")
},
"Valider": function() {
var icon = $('.iconSelected .iconSelName').html();
if (icon == undefined) {
icon = ''
}
_callback(icon)
$(this).dialog('close')
}
})
$('#mod_selectIcon').dialog('open')
})
}
$('#div_templateTest').off('click','.chooseImage').on('click','.chooseImage', function() {
var bt = $(this)
chooseImage(function(_icon) {
bt.closest('.input-group').find('.imgMod').value(_icon)
})
})
plugins/plugin_name/desktop/modal/modal.uploadImage.php :
if (!isConnect()) {
throw new Exception('{{401 - Accès non autorisé}}');
}
$pluginName = 'wifilightV2';
$rootPath = __DIR__ . '/../../';
sendVarToJS([
'tabimg' => init('tabimg'),
'pluginName' => init('pluginName', $pluginName),
'rootPath' => init('rootPath', $rootPath)
]);
?>
<div style="display: none;" id="div_iconSelectorAlert"></div>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#tabimg" aria-controls="home" role="tab" data-toggle="tab"><i class="far fa-images"></i> {{Image}}</a></li>
</ul>
<div class="tab-content" style="overflow-y:scroll;">
<div role="tabpanel" id="tabimg" style="width:calc(100% - 20px);">
<span class="btn btn-default btn-file pull-right">
<i class="fas fa-cloud-upload-alt"></i> {{Envoyer}}<input id="bt_uploadImg" type="file" name="file" multiple="multiple" data-path="" style="display: inline-block;">
</span>
<div class="imgContainer">
<div id="div_treeFolder">
<ul id="ul_Folder">
<?php
foreach (ls($rootPath, 'data', false, array('folders')) as $folder) {
echo '<li data-jstree=\'{"opened":true}\'><a data-path="' . $rootPath . $folder . '">' . $folder . '</a></li>';
}
?>
</ul>
</div>
<div id="div_imageGallery">
</div>
</div>
</div>
<?php
include_file('3rdparty', 'jquery.tree/jstree.min', 'js');
?>
<script>
$( document ).ready(function() {
$('#div_treeFolder').off('click').on('select_node.jstree', function(node, selected) {
if (selected.node.a_attr['data-path'] != undefined) {
var path = selected.node.a_attr['data-path'];
printFileFolder(path);
var ref = $('#div_treeFolder').jstree(true)
var sel = ref.get_selected()[0];
ref.open_node(sel);
var nodesList = ref.get_children_dom(sel)
if (nodesList.length != 0) {
return
}
jeedom.getFileFolder({
type : 'folders',
path : path,
error: function(error) {
$('#div_alert').showAlert({message: error.message, level: 'danger'})
},
success : function(data) {
for (var i in data) {
node = ref.create_node(sel, {"type":"folder","text":data[i],state:{opened:true},a_attr:{'data-path':path+data[i]}})
$('li#'+node+' a').addClass('li_folder')
}
}
})
}
})
$("#div_treeFolder").jstree({
"core" : {
"check_callback": true
}
});
$('#div_imageGallery').on('click', '.divIconSel', function() {
$('.divIconSel').removeClass('iconSelected');
$(this).closest('.divIconSel').addClass('iconSelected');
})
$('#div_imageGallery').on('dblclick', '.divIconSel', function() {
$('.divIconSel').removeClass('iconSelected');
$(this).closest('.divIconSel').addClass('iconSelected');
$('#mod_selectIcon').dialog("option", "buttons")['Valider'].apply($('#mod_selectIcon'));
})
$('a[href="#tabimg"]').on('click', function () {
$('#div_treeFolder').find('a:first').click();
})
$('a[href="#tabicon"]').on('click', function () {
$.hideAlert();
})
});
$('#bt_uploadImg').fileupload({
add: function (e, data) {
let currentPath = $('#bt_uploadImg').attr('data-path');
data.url = 'plugins/'+pluginName+'/core/ajax/'+pluginName+'.ajax.php?action=uploadCustomImg&filepath='+currentPath;
data.submit();
},
done: function(e, data) {
if (data.result.state != 'ok') {
$('#div_iconSelectorAlert').showAlert({message: data.result.result, level: 'danger'});
return;
}
$('#div_iconSelectorAlert').showAlert({message: 'Fichier(s) ajouté(s) avec succès', level: 'success'});
$('.jstree-clicked').click();
}
});
$('#div_imageGallery').off('click').on('click', '.bt_removeImg',function() {
$.hideAlert();
var filepath = $(this).attr('data-realfilepath');
bootbox.confirm('{{Êtes-vous sûr de vouloir supprimer cette image}} <span style="font-weight: bold ;">' + filepath + '</span> ?', function(result) {
if (result) {
jeedom.removeImageIcon({
filepath : filepath,
error: function(error) {
$('#div_iconSelectorAlert').showAlert({message: error.message, level: 'danger'});
},
success: function(data) {
$('#div_iconSelectorAlert').showAlert({message: 'Fichier supprimé avec succès', level: 'success'});
$('.jstree-clicked').click();
}
})
}
})
});
function printFileFolder(_path) {
$.hideAlert();
jeedom.getFileFolder({
type : 'files',
path : _path,
error: function(error) {
$('#div_alert').showAlert({message: error.message, level: 'danger'})
},
success : function(data){
let realPath = _path.substr(_path.search('plugins/'));
let realPathName = _path.substr(_path.search('data/'));
$('#bt_uploadImg').attr('data-path', realPath);
$('#div_imageGallery').empty();
var div = '';
for (var i in data) {
div += '<div class="divIconSel divImgSel">';
div += '<div class="cursor iconSel"><img class="img-responsive" src="'+realPath+data[i]+'"/></div>';
div += '<div class="cursor iconSelName" style="visibility: hidden;font-size:1px">'+realPathName+data[i]+'</div>';
div += '<div class="iconDesc">'+data[i].substr(0,15)+'</div>';
div += '<a class="btn btn-danger btn-xs bt_removeImg" data-realfilepath="'+realPath+data[i]+'"><i class="fas fa-trash"></i> {{Supprimer}}</a>';
div += '</div>';
}
$('#div_imageGallery').append(div)
}
})
}
</script>
</div>
<script>
$(function() {
$('.imgContainer').show();
$('.div_imageGallery').show();
var path= rootPath+'data/';
$('#div_treeFolder').jstree('select_node', 'ul > li:first');
printFileFolder(path);
})
</script>