问题描述
我已经搜索了一些有效的图像存储解决方案,并获得了非常令人兴奋的一行,您应该只存储图像路径而不是整个图像存储在数据库中。
I've googled for some efficient image storage solutions and got very exciting line to read that you should store only image path rather that whole image in the database.
现在我正在开发一个基于MVC的Java Web项目,并且对这个主题非常了解。具体来说,我想知道我是否能够从我的 Servlet
将我的图像直接保存到任何图像托管网站,它立即为我提供了一个链接,我将存储在我的数据库列中未来的使用?
Now I am working on a Java web project based on MVC and is willing too know extra about this topic. Specifically I want to know if I am able to save my image directly to any image hosting website from my Servlet
which instantly provide me a link that I will store in my database column for future use?
推荐答案
这确实是推荐的。在数据库中存储二进制数据在语义上没有任何意义。你不能索引它,也不能搜索它,等等。这只是死的数据。您可以将其直接存储在磁盘文件系统上,然后将其唯一标识符(通常只是文件名)存储在数据库中。文件名可以是可索引的varchar(因此允许更快的 SELECT ... WHERE
)。
That's indeed recommended. Storing binary data in a database makes semantically no utter sense. You cannot index it, nor search in it, etcetera. It's just "dead" data. You can store it as good directly on the disk file system and then store its unique identifier (usually just the filename) in the database. The filename can be a varchar which is indexable (which thus allows for faster SELECT ... WHERE
).
我不确定这里的具体问题是什么。您应该意识到传输字节毕竟只是读取任意并将其写入仲裁。你的具体问题应该是,如何获得上传图像的 InputStream
?或如何获得 OutputStream
到本地磁盘文件系统?,或者如何获得 OutputStream
到图像托管网站?。
I'm not sure what's your concrete problem here. You should realize that transferring bytes is after all just a matter of reading an arbitrary InputStream
and writing it to an arbitratry OutputStream
. Your concrete question should rather be, "How do I get an InputStream
of the uploaded image?", or "How do I get an OutputStream
to the local disk file system?", or maybe "How do I get an OutputStream
to the image hosting website?".
获取上传图片的 InputStream
很简单。所有体面的文件上传API都提供了一种 getInputStream()
方法。另请参见获取 OutputStream
到也很简单。只需构建一个。
Getting the uploaded image's InputStream
is easy. All decent file upload APIs offer kind of a getInputStream()
method. See also How to upload files to server using JSP/Servlet? Getting an OutputStream
to a File
on the local disk file system is also easy. Just construct a FileOutputStream
around it.
File file = File.createTempFile(prefix, suffix, "/path/to/uploads");
InputStream input = uploadedFile.getInputStream();
OutputStream output = new FileOutputStream(file);
// Now write input to output.
String uniqueFileName = file.getName();
// Now store filename in DB.
获取 OutputStream
到其他主机是一个故事。你想怎么连接它?使用FTP?使用。或者使用HTTP(eek)?使用或。
Finally, in order to get this image by URL (by either <img src>
or direct request or whatever), read this answer: Reliable data serving.
这篇关于如何只在图像数据库中存储图像路径(URL)而不是图像本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!