Java Web App上传和加载图像 [英] Java Web App upload and load images

查看:95
本文介绍了Java Web App上传和加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在使用Spring Framework开发简单的Web应用程序。

So, i am developing simple web application using Spring Framework.

应用程序用户可以上传图像。

The application users can upload images.

存储/加载图像的最佳做法是什么?

What is best practices for storing/loading images?

我在某个论坛找到了解决方案,有人建议将文件存储到user.dir目录。

I found solution on some forum, where someone suggested to store files to user.dir directory.

好的,我也这样做。

当用户上传图片时我将图像存储到user.dir目录。

When user upload image i store the image to user.dir directory.

现在,我有一个问题:如何将图像从user.dir目录加载到页面?

Now, i have a question: how to load image from user.dir directory to page?

 <img src="path/to/dir/where/images/stored"/>


推荐答案

最佳做法是将此类数据存储在webapp的外部树,以避免重新部署问题。它们存储的确切位置更符合惯例,user.dir确实是一个合理的选择。

Best practice is indeed to store such data outside the webapp's tree to avoid issues on redeployment. Where exactly they get stored is more a matter of convention, user.dir can indeed be a reasonable choice.

你不能直接提供这些文件,通常它已经完成了通过创建一个映射到例如 images / * 的servlet来解析请求URL(例如< img src =approot / images / apic.jpg /> )并根据该网址获取并提供 path / to / dir / where / images / stored / apic.jpg 。作为一个额外的好处,servlet可让您完全控制下载内容,何时以及由谁,也许您将在以后的应用程序生命周期中进行此类控制。

You can't serve these files directly though, commonly it's done by creating a servlet mapped to eg images/* that parse the request URL (eg <img src="approot/images/apic.jpg"/>) and based on that url if fetches and serves path/to/dir/where/images/stored/apic.jpg. As an added bonus that servlet gives you full control over what gets downloaded, when and by who, maybe you will need this kind of control later on in the application lifecycle.

您可以使用 getPathInfo 检索servlet名称后面的URL部分,为输出设置正确的MIME类型,并将请求的文件流式复制到servlet的输出。

You can use getPathInfo to retrieve the part of the URL following the servlet name, set the correct MIME type for the output, and streamcopy the requested file to the servlet's output.

可以在 BalusC的博客

这篇关于Java Web App上传和加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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