通过restAPI显示图片的正确方式 [英] Correct way to display image through restAPI

查看:44
本文介绍了通过restAPI显示图片的正确方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试通过 rest API 显示个人资料图片.我让它工作了,但我觉得这不是正确的方法.

I am currently trying to show profile pictures through rest API. I got it to work, but I got a feeling it is not the correct way to do it.

所以,在 API 中我得到了一个控制器:

So, on in the API i got a controller:

public function getUserprofilepicAction(Request $request) {
    /**
    * Handle stuff
    */

    $file = $user->getWebPath();
    $type = 'image/jpeg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
}

现在 API 调用是这样的:

Now the API call is something like this:

<somesite>/api/user/userprofilepic.json?userId=84

为了查看网页上的图片:

And in order to view the image on the webpage:

<img src = <somesite>/app_dev.php/api/user/userprofilepic.json?userId=84>

所以现在我想知道,在 symfony2 中通过 restAPI 发送/查看图片的最佳实践究竟是什么.

So now I wonder, what exactly is the best practises regarding sending/viewing pictures through restAPI in symfony2.

-干杯

推荐答案

您在控制器中做得很好.

You are doing it right in the controller.

  1. 获取图片
  2. 获取类型(以及其他信息,例如长度)——总是为您提供 jpeg 格式?
  3. 设置 HTTP 标头(Content-Type 和其他)
  4. 返回二进制数据(文件内容)

还有其他方法可以实现:

There are other ways to achieve that:

  • 通过base64编码的字符串:如果你想返回一个字符串而不是二进制数据,你可以将图像编码为base64字符串,然后通过网络发送.问题是响应的大小.base64 编码的字符串比二进制数据大 33%.

  • Via base64 encoded string: If you want to return a string instead of binary data, you can encode your image as a base64 string and then send it over the network. The problem is the size of the response. A base64 encoded string is 33% bigger than the binary data.

通过网络路径:如果你想避免读取图像,每次发送二进制文件,你可以只返回图像的 URL(例如 http://example.com/u/img.jpeg) 并让客户端执行请求.这样,您在操作背后就没有任何业务逻辑.每次有人想要头像,他只需要查询yhe图片的URL.对于此解决方案,您需要将图像上传到 web/uploads/pics/ 等公共目录中.

Via web path: If you want to avoid reading the image, send the binary everytime, you could just return the URL of the image (ex. http://example.com/u/img.jpeg) and let the client do the request. This way you don't have any business logic behind the action. Everytime someone wants the profile picture, he just needs to query the URL of yhe image. For this solution you need to upload your images in a public dir like web/uploads/pics/.

PS:如果你想遵循 REST 的想法,我会为路由做类似 /api/user/84/profilepicture 的事情.

PS: I would do something like <somesite>/api/user/84/profilepicture for the routing, if you want to follow REST idea.

这篇关于通过restAPI显示图片的正确方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆