Я использую таблицу «Вложения», чтобы сохранить в базе данных имя файла и другие поля, и сохраняю файлы в своей файловой системе. Обычно я связываю вложение с таблицей реестра через таблицу RegistryAttachment.
Я успешно сохраняю несколько файлов, но когда я загружаю файлы для определенного реестра, я хочу видеть их такими же, как при первой загрузке .
Я пытаюсь это сделать, используя следующий код:
Действие контроллера >
Код: Выделить всё
public function actionLoadMultiple($registryId = NULL){
$model = new Attachment();
if(!$registryId){
$model->files = [];
$registryId = 6;//For example
$registry = \app\models\Registry::findOne($registryId);
$registryAttachments = $registry->attachments;//Find all Attachment record for registryId
foreach($registryAttachments as $attachment){
$model->files[$attachment->original_filename] = $attachment->filePath();
}
}
if (Yii::$app->request->isPost) {
//Loading the files in the model.
//After I load them, I save them using the model function uploadMultiple
$model->files = UploadedFile::getInstances($model, 'files');
$loadedFiles = $model->uploadMultiple();
if ($loadedFiles) {
// file is uploaded successfully
foreach($loadedFiles as $originalFileName=>$fileName){
$attachment = new Attachment();
$attachment->section = $model->section?: 'oth';
$attachment->description = $model->description ?: 'Other';
$attachment->filename = $fileName;
$attachment->original_filename =$originalFileName;
if(!$attachment->save()){
$attachment->removeFile();
return ['error'=>\Yii::t('app','Error saving attachments to db. Please contact an administrator')];
}
}
return $this->redirect(['index']);
}
}
return $this->render('load_multiple',['model'=>$model]);
}
Код: Выделить всё
public function uploadMultiple(){
$files = $this->files;
$section = $this->section ?: '';
if(!$files){
return false;
}
$fileNameList = [];
$path = Utility::getAttachmentsBasePath();
$count = 1;
foreach ($files as $file) {
if (!$section) {
$section = 'oth';
}
$filename = \app\models\Attachment::generateFilename($file->name);
//I set the path to the right folder
$completePath = $path . '/' . $section . '/' . $filename;
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$completePath = str_replace('/', '\\', ($completePath));
}
if (!$file->saveAs($completePath)) {
Yii::error("Error loading file - error code {$file->error}", "upload");
return ['error' => \Yii::t('app', 'Error saving files. Please contact an administrator')];
}
if (isset($fileNameList[$file->name])) {
$fileNameList[$file->name . '_' . $count] = $filename ;
$count++;
} else {
$fileNameList[$file->name] = $filename;
}
}
return $fileNameList;
}
Код: Выделить всё
Если к выбранному реестру прикреплено 3 файла результат следующий:

.
В этой настройке у меня возникли следующие проблемы:
- Я хочу увидеть содержимое каждого файла, но это не работает.
- Когда я загружаю новый файл, виджет удаляет уже загруженные файлы.
- Кнопка удаления отдельного файла не работает
Подробнее здесь: https://stackoverflow.com/questions/604 ... es-preview