首先
我的图像模型很简单
return [ 'id' => 'ID', 'parent_id' => 'Parent ID', 'photo' => 'Photo', <= just for filename ];
- 案例是创建父模型,然后保存然后重定向到表单以上传与其父模型相关的图像。
- 所有上传功能都可以正常工作,但没有删除功能
这是我的上传图片表格
echo FileInput::widget([
'model' => $photo,
'attribute' => 'photo',
'options'=>[
'accept'=>'image/*',
'multiple'=>true
],
'pluginOptions' => [
'uploadUrl' => Url::to(['/controller/upload', 'id'=> $parent->id]),
'initialPreview'=>$pre-initViews-data,
'initialPreviewAsData'=>true,
'initialCaption'=>"Foto Tersangka",
'initialPreviewConfig' => $pre-initConfigs-data,
'overwriteInitial'=>true,
//'deleteUrl'=> Url::to(['/controller/deletephoto']), <= case 2
'showPreview' => true,
'showRemove' => false,
'showUpload' => false,
'maxFileSize'=>2800
],
'pluginEvents' => [
'fileuploaded'=>"function(event, data, previewId, index){
console.log(data);
}",
]
]);
这里是我的控制器端
$imageFile = UploadedFile::getInstance($model, 'photo');
$directory = Yii::$app->basePath. '/images/';
if ($imageFile) {
$fileName = Yii::$app->security->generateRandomString(). '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath) && $model->save(false)) {
$path = '/images/temp/' . $fileName;
Image::thumbnail($directory.$fileName, 120, 120)
->save(Yii::$app->basePath.$path, ['quality' => 80]);
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
}
}
并将生成如下 JSON 数据:
{
"initialPreview": "\/web\/images\/Kl1IJOabLs5ENzzgkuW8ln_TILcDumy9.png",
"initialPreviewConfig": {
"caption": "",
"width": "90px",
"key": 38,
"url": "\/web\/index.php?r=controller%2Fdeletephoto",
"extra": {
"id": 38
}
}
}
问题
我尝试不同的方式,例如:
案例 1:在表单小部件中没有 pluginOptions => deleteUrl'=> Url::to(['/controller/deletephoto']),上传过程成功,来自控制器的响应 initialPreview 按预期覆盖初始,但 initialPreviewConfig 似乎不合适,所以删除按钮不起作用/单击时不提供任何过程。
案例 2:在带有 pluginOptions => deleteUrl'=> Url::to(['/controller/deletephoto']) 的表单小部件上,按预期上传过程,但是当我单击删除按钮后操作没有解析键如下
查询字符串
r : controller/deletephoto 表单数据键 : {empty key}
最后
我花了很多时间,请检查我的代码,有什么问题吗?
非常感谢您的帮助。
更新问题已解决
经过漫长的时间后,我终于找到了方法..替换
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
和
return Json::encode([
'initialPreview' => \Yii::$app->request->BaseUrl.'/images/'.$fileName,
'initialPreviewConfig' => [
[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
],
],
]);
不知道为什么会这样,