yii2,kartik文件输入,ajax上传方案:通过上传第二个文件,第三个文件等等,上一个文件的标签被错误地替换

问题描述

我正在使用kartik fileinput插件(bootstrap-fileinput v5.1.2)进行Yii2项目。我正在使用ajax上传方案,一次上传一个文件,并且我已经自定义了页脚模板,其中包含用于捕获其他数据的输入,类似于https://plugins.krajee.com/file-input-ajax-demo/7

在“ filebatchselected”事件中,我自动开始上传。之后,当用户更改页脚模板中的输入值时,我切换了保存按钮(在“ otherActionButtons”中自定义)的可见性,该按钮一旦被用户按下,就会触发ajax更新

到目前为止,一切正常,但是当我上传第二个文件,第三个文件等等时...先前和已经上传文件的输入值将被覆盖/重新初始化...

这是我的代码

查看:

<?
$categoria = ...

$footerTemplate = '<div class="file-thumbnail-footer">' .
'    <div class="file-footer-caption" title="{caption}">' .
'        <div class="file-caption-info">{caption}</div>' .
'        <div class="file-size-info">{size}</div>' .
'    </div>' .
     $form->field(new File,"titolo",['enableClientValidation' => false])->textInput(["value"=>"{titolo}","id"=>"file-titolo-{ID}","class" => "mb-1 file-titolo","placeholder" => "Breve descrizione del file..."])->label(false).
'    {progress}{indicator}{actions}' .
'</div>';

$initialPreview = [...];
$initialPreviewConfig = [...];
$initialPreviewThumbTags = [...];

echo $form->field($model,"_filesGenerici")->widget(FileInput::className(),[
    'options'=>[
        "id" => $idWidget = "fileInputDocAusGenerici$categoria",],'pluginoptions' => [
        "initialPreview" => $initialPreview,"initialPreviewConfig" => $initialPreviewConfig,"initialPreviewThumbTags" => $initialPreviewThumbTags,'showUpload' => false,'showCancel' => false,'showRemove' => false,'uploadUrl' => Url::to(['files-generici/create']),'uploadExTradata' => [
            "dipendente_CodFsc"=>$model->CodFsc,"categoria"=>$categoria,"anno"=>$anno,"mese"=>$mese,"previewThumbTags" => [
            "{ID}" => "","{titolo}" => "","deleteUrl" => Url::to(['files-generici/delete']),"maxFileSize" => 2048,"overwriteInitial" => false,'fileActionSettings'=>[
            'showUpload'=>false,'showDrag'=>false,"validateInitialCount" => true,"otherActionButtons" => <<<HTML
            <button type="button" class="kv-file-edit btn btn-sm btn-kv btn-default btn-outline-secondary display-hidden text-success" title="qwerty"{dataKey}>
                <i class="fas fa-save"></i>
            </button>
        HTML,"layoutTemplates" => [
            'footer' => $footerTemplate,"pluginEvents" => [
        "filebatchselected" => new \yii\web\JsExpression(<<<JS
            function(event,files) {
                if(confirm("Confermi il caricamento del file?"))
                    $("#$idWidget").fileinput("upload");
                else
                    $("#$idWidget").fileinput("clear");
            }
        JS),"filepredelete" => "function(event,key) {
            return !confirm('Sei sicuro di voler eliminare questo file?');
        }",]);

$urlUpdateFilesGenerici = Url::to(["$controller/update"]);
$this->registerJs(<<<JS
    $(document).on("keyup paste change",".file-titolo",function(){
        $(this).closest(".file-thumbnail-footer").find(".kv-file-edit").removeClass("display-hidden");
    });
        
    $(document).on('click','#tabFiles$categoria .kv-file-edit',function() {
        console.log("processing");
        
        let btn = $(this),key = btn.data('key'),titolo = btn.closest(".file-thumbnail-footer").find(".file-titolo").val();
            periodo = btn.closest(".file-thumbnail-footer").find(".daterange").val();
        
        $.post("$urlUpdateFilesGenerici?key="+key,{titolo: titolo,mese: $mese,anno: $anno,periodo: periodo},function(data,textStatus,jqXHR){
            btn.addClass("display-hidden");
        });
    }); 
JS);
?>

控制器:

<?
public function actionCreate($dipendente_CodFsc,$anno,$mese)
{        
    $uploadedFile = UploadedFile::getInstances(new Dipendente,'_filesGenerici')[0];
    
    $model = new FileGenerico([
        "_FILE" => $uploadedFile,'cliente' => Yii::$app->user->identity->user,'dipendente_CodFsc' => $dipendente_CodFsc,'anno' => $anno,'mese' => $mese,]);
    
    $post = Yii::$app->request->post();
    
    if ($model->load($post,"") && $model->save()) 
    {
        $initialPreview = $model->isText ? $model->blob ?? $model::find()->select("blob")->where(["id"=>$model->id])->scalar()
            : ($model->isImageRaster ? $model->biggest : $model->sourceFile);
        
        $initialPreviewConfig = [
            [
                "previewAsData" => true,"size" => $model->size,"key" => $model->id,"fileId" => $model->id,]
        ];
        
        if(!$model->isImageRaster){
            $initialPreviewConfig["type"]=$model->type4FI;
        }
        if(($model->isVideo) || ($model->isAudio)){
            $initialPreviewConfig["filetype"]=$model->type;
        }
        
        $initialPreviewThumbTags = [
            [
                "{ID}" => $model->id,"{titolo}" => $model->titolo,"{created_at}" => "<b>Caricato il:</b> ".Yii::$app->formatter->asDate($model->created_at),]
        ];

        $config = [
            "initialPreview" => $initialPreview,];
        
        Yii::$app->response->data = $config;
    }
    else 
        die('<pre>'.print_r($model->errors,1).'</pre>');
}
?>

你能帮我吗?

解决方法

我希望这可以帮助某人。问题在于,文件上传后,插件会从缓存中还原以前的拇指标签...我自己的解决方案:当ajax更新完成时,手动更新缓存标签。

<<<JS
$.post("$urlUpdateFilesGenerici?key="+key,{titolo: titolo,mese: $mese,anno: $anno,periodo: periodo},function(data,textStatus,jqXHR){
    btn.addClass("display-hidden");

    let index = $("#$idWidget").data("fileinput").previewCache.data.content.length - 1;    
    $("#$idWidget").data("fileinput").previewCache.data.tags[index]["{titolo}"] = titolo;//THIS DO THE TRICK
});
JS;