gpt4 book ai didi

php - 在 Laravel 7 中返回响应图像

转载 作者:行者123 更新时间:2023-12-05 08:15:47 24 4
gpt4 key购买 nike

我正在尝试创建一个迷你随机图像生成器,作为我尝试过的开始:

Route::get('/img/UoJb9wl.png','Image@random');

我所做的就是归还这个

return '<img src="/assets/fe/img/welcome.jpeg" alt="Smiley face" width="200">';

然后,我在实时站点上进行了测试:

如果我转到 URL,我会看到图像已加载

https://www.bunlongheng.com/img/UoJb9wl.png

enter image description here

如果我在类似 JSFiddle 的网站上导入像这样

<img src="https://www.bunlongheng.com/img/UoJb9wl.png">

我看不到。

为什么?


编辑

尝试 #2

return env('APP_URL').'/assets/fe/img/welcome.jpeg';

我现在返回图片路径

但我的 JSFiddle 中仍然没有任何渲染还是

<img src="https://www.bunlongheng.com/img/UoJb9wl.png">

最佳答案

这不起作用,因为您的 Controller 返回的不是图像,而是 HTML 代码。

当您在浏览器中使用此地址时,它会向您的服务器发送请求,服务器会以包含 <img src="..."/> 的 HTML 进行响应。带有指向实际图像的链接,因此浏览器会显示它。

当您尝试在 <img src="..."/> 中使用相同的地址时,您的服务器仍然返回不是图像的 HTML 代码,因此显然不会显示。


  1. 您始终可以提供图片本身:
function random()
{
return response()->file(/* path to image file */);
}
  1. 你可以查看Accept标题以确定要响应的内容:
function random(Request $request)
{
$accept = $request->header('Accept');
if (strpos($accept, 'text/html') !== false) {
return response()->html('<img ...');
} elseif (strpos($accept, 'image/') !== false) {
return response()->file(...);
}
abort(403, 'No content for requested type');
}

关于php - 在 Laravel 7 中返回响应图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67098708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com