you should store only image path rather that whole image in the database.
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 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?
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?".
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.
Getting an OutputStream
to some other host is a story apart. How do you want to connect to it? Using FTP? Use FTPClient#appendFileStream()
. Or using HTTP (eek)? Use URLConnection#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.