我有一个小问题。我无法查看后端web文件夹之外的图像。
常见别名\config\main:
'aliases' => [
'@upload' => dirname(dirname(__DIR__)).'/upload',
],
查看数据提供者:
[
'format' => 'raw',
'label' => 'Immagine',
'value' => function ($data) {
return Html::img(Yii::getAlias('@upload') . $data->codice_prodotto . '/' . $data->immagine, ['width' => '70px', 'class' => 'img-thumbnail']);
},
],
我能下决心吗?谢谢
如果http服务器无法访问您的文件,则无法直接下载。
您可以:
- 将上传目录移动到http服务器可访问的目录
- 创建从私有目录读取文件并将其流式传输到浏览器的操作(您可以使用yii\web\Response::sendFile((函数(
将文件流式传输到浏览器
请阅读这篇官方文档文章以深入理解这一点:https://www.yiiframework.com/doc/api/2.0/yii-web-response#sendFile((-详细
案例的操作代码示例:*
public function actionFile($filename)
{
$storagePath = Yii::getAlias('@upload');
// check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
if (!preg_match('/^[a-z0-9]+.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
throw new yiiwebNotFoundHttpException('The file does not exists.');
}
return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}
并查看数据提供程序配置:*
[
'format' => 'raw',
'label' => 'Immagine',
'value' => function ($data) {
return Html::img(Url::to(['/path/to-streaming-action/file', 'filename' => $data->codice_prodotto . '/' . $data->immagine]), ['width' => '70px', 'class' => 'img-thumbnail']);
},
],
*请注意,此代码还没有准备好复制粘贴,请仔细阅读并尝试理解原理,然后在代码中实现它