You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

CS-Cart模块file类型设置项如何获取完整上传文件路径?

解决CS-Cart模块设置中文件完整路径的获取问题

我来帮你搞定这个文件路径的坑!你遇到的数字目录(比如1/)其实是CS-Cart的文件存储位置ID对应的目录——CS-Cart会把上传的文件按存储位置(本地/云存储等)分到不同子目录下,这个ID存在files_storage_location表中,默认本地存储的ID通常是1,但不同环境可能有变化,硬编码肯定不行。

下面给你两种场景下的正确解决方案:

1. 在PHP代码中获取完整服务器路径

CS-Cart提供了官方函数fn_get_files_storage_location_path(),专门用来获取对应存储位置的根路径,完全适配不同配置:

// 获取当前系统默认的文件存储位置ID
$storage_location_id = Registry::get('config.files_storage_location_id');

// 获取该存储位置的服务器根路径(比如/path/to/site/root/var/files/1/)
$storage_root_path = fn_get_files_storage_location_path($storage_location_id);

// 拼接完整文件路径
$full_file_path = $storage_root_path . Registry::get('addons.my_addon.attach_file');

这样得到的路径就是准确的,不管存储位置ID是多少都能适配。

2. 在Smarty模板中获取完整路径

如果需要在模板里展示或使用这个路径,可以用模板函数get_files_storage_location_path

{* 捕获存储位置的根路径 *}
{capture name="storage_path"}{get_files_storage_location_path id=$config.files_storage_location_id}{/capture}

{* 拼接完整文件路径 *}
{assign var="full_file_path" value=$smarty.capture.storage_path|cat:$addons.my_addon.attach_file}

额外:获取文件的可访问URL

如果需要的是前端能访问的URL(而不是服务器本地路径),可以用对应的fn_get_files_storage_location_url()函数:

$storage_url = fn_get_files_storage_location_url($storage_location_id);
$file_access_url = $storage_url . Registry::get('addons.my_addon.attach_file');

为什么之前的方法不对?

Registry::get('config.dir.files')仅返回基础的var/files/目录,但实际文件是存在对应存储位置的子目录下的。使用官方提供的函数,能自动适配所有存储配置(包括本地存储ID变化、云存储等场景),避免硬编码带来的兼容性问题。

内容的提问来源于stack exchange,提问作者impulsgraw

火山引擎 最新活动