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.
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?
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).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
InputStreamand writing it to an arbitratryOutputStream. Your concrete question should rather be, “How do I get anInputStreamof the uploaded image?”, or “How do I get anOutputStreamto the local disk file system?”, or maybe “How do I get anOutputStreamto the image hosting website?”.Getting the uploaded image’s
InputStreamis easy. All decent file upload APIs offer kind of agetInputStream()method. See also How to upload files to server using JSP/Servlet? Getting anOutputStreamto aFileon the local disk file system is also easy. Just construct aFileOutputStreamaround it.Getting an
OutputStreamto some other host is a story apart. How do you want to connect to it? Using FTP? UseFTPClient#appendFileStream(). Or using HTTP (eek)? UseURLConnection#getOutputStream()or HttpClient. You should ask a more finer grained question about that if you stucks.Finally, in order to get this image by URL (by either
<img src>or direct request or whatever), read this answer: Reliable data serving.