如何解决Drupal 上传然后移动不会更新文件列表中的路径或文件名
我有一个使用“managed_file”上传到临时文件夹的自定义表单。以编程方式,然后我加载该文件并将其移动到其永久存储(覆盖具有 * 名称的任何现有文件),例如
// Upload file
$upfile = $this->entityTypeManager->getStorage('file')->load($fid);
// Source and destination
$sourceUri = $this->fileSystem->realpath($upfile->getFileUri());
$destinationUri = $this->fileSystem->realpath(\Drupal::config('system.file')->get('default_scheme') . "://") . '/x/y/z/XYZ_NEW.pdf';
// Move and overwrite
$this->fileSystem->move($sourceUri,$destinationUri,FileSystemInterface::EXISTS_REPLACE);
所有这些都有效(即文件被物理移动到正确名称的正确位置);但是,列表中显示的文件(即 /admin/content/files)仍将不正确的临时文件夹显示为 URI。
基本上列表页面中的文件似乎显示了先前成功移动的文件的原始文件路径和名称*。
如果我使用不正确的 URI 加载此文件,即使用不正确的临时路径,数据将加载,但不会有文件信息(因为它不存在。同时通过浏览器在列表下单击文件名将显示页面未找到且显示旧 URL 的 URL,即 /system/temporary?file=XYZ.pdf)。
如果我通过正确的 URI 加载此文件,即使用正确的目标路径,则找不到文件 - 如果我直接在浏览器中转到该路径,则相同。
托管文件似乎不知道它已被移动。如何解决此错误?
解决方法
docs for FileSystem::move 表示“将文件移动到新位置,无需更改数据库或调用挂钩。”
因此您将需要使用新值更新文件实体..
试试这个,未经测试:
// Upload file
$upfile = $this->entityTypeManager->getStorage('file')->load($fid);
// Source and destination
$sourceUri = $this->fileSystem->realpath($upfile->getFileUri());
$destinationUri = $this->fileSystem->realpath(\Drupal::config('system.file')->get('default_scheme') . "://") . '/x/y/z/XYZ_NEW.pdf';
// Move and overwrite
$newFileName = $this->fileSystem->move($sourceUri,$destinationUri,FileSystemInterface::EXISTS_REPLACE);
// Set the new file path on the file entity.
$upfile->setFileUri($newFileName);
// Set the file to permanent if needed.
$upfile->setPermanent();
// Save entity with changes.
$upfile->save();
不过我没有测试这个。
您可以在 docs here
事实证明基于类的方法不会更新数据库
程序版本可以
https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_move/8.9.x
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。