Spring-MVC, Java : Creating URL for image saved on FileSystem

我的梦境 提交于 2020-02-02 15:19:26

问题


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.

For example : Image is saved at

/home/username/datadir/personid.png

I would like to give the url something like :

domainname.com/personid.png

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.. :-)


回答1:


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);
}

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




回答2:


First of all you can do it with two ways, first in your tomcat's conf folder there's a file named as server.xml, add below line into it

<Context docBase="YOUR/FILE/PATH"   path="/" />

After that if you save your files into YOUR/FILE/PATH tomcat will serve it to outside as domainname.com/filename

The second way is more complicated and you have to google it a bit. You can open a controller that serves your images to outside as Master Slave answered.

Rg.



来源:https://stackoverflow.com/questions/29943925/spring-mvc-java-creating-url-for-image-saved-on-filesystem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!