0

我正在使用 kartik 文件输入插件(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,
            "initialPreviewConfig" => $initialPreviewConfig,
            "initialPreviewThumbTags" => $initialPreviewThumbTags,
        ];
        
        Yii::$app->response->data = $config;
    }
    else 
        die('<pre>'.print_r($model->errors,1).'</pre>');
}
?>

你能帮我吗?

4

1 回答 1

0

我希望这可以帮助某人。问题是,上传文件后,插件从缓存中恢复以前的拇指标签......我自己的解决方案:在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;
于 2020-11-11T08:48:54.113 回答