Spring-MVC,Java:为保存在FileSystem上的图像创建URL [英] Spring-MVC, Java : Creating URL for image saved on FileSystem

查看:98
本文介绍了Spring-MVC,Java:为保存在FileSystem上的图像创建URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Spring-MVC应用程序,在该应用程序中,对于用户而言,我们将缩略图保存在文件系统本身上.现在进行聊天,我想为保存在文件系统上的缩略图创建一个URL,并将其传递到前端.

I am working on a Spring-MVC application in which for the user, we are saving the thumbnail on the filesystem itself. Now for chat, I want to create a URL for the thumbnail saved on the filesystem and pass it on in the frontend.

例如:图像保存在

/home/username/datadir/personid.png

我想给网址类似:

domainname.com/personid.png

请注意,PersonId是唯一的,因此我可以使用该约束.保存图像的部分已经完成,我只是不知道如何使用保存在文件系统中的文件来创建图像URL.

Please note PersonId is unique, so I can use that constraint. The part to save the image is complete, I just don't know how to create an image URL out of the file saved on File-System.

任何帮助都会很好.非常感谢..:-)

Any help would be nice. Thanks a lot.. :-)

推荐答案

您应在此调用中加入请求处理程序,例如

You should intermediate this call with a request handler, something like

@RequestMapping("/image/{personId}")
@ResponseBody
public HttpEntity<byte[]> getPhoto(@PathVariable String personId) {
    byte[] image = org.apache.commons.io.FileUtils.readFileToByteArray(new File([YOUR PATH] + File.separator + personId + ".png"));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG); 
    headers.setContentLength(image.length);
    return new HttpEntity<byte[]>(image, headers);
}

请注意,您可以使用内容分析来确定适当的媒体类型,例如在 Apache Tika 的帮助下.这样,您就不必存储文件名或对扩展名进行硬编码

Note also that you can use content analysis to determine the proper media type e.g. with the help of Apache Tika. This way you don't have to store filename, or hard-code the extension

这篇关于Spring-MVC,Java:为保存在FileSystem上的图像创建URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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