How to I retrieve an image from a URL and store it as a Blob in Java (google app engine)
I understand how to fetch a URL text page a开发者_Go百科nd loop over the results
URL url = new URL(this.url);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
....
How would I do this to fetch an image and store it as a Blob?
Just get it straight as InputStream
and use PreparedStatement#setBinaryStream()
to store it. It's binary data, not character data, so a Reader
would only messup things, you don't want to have that.
In a nutshell:
InputStream input = imageUrl.openStream();
// ...
statement = connection.prepareStatement("INSERT INTO image (content) VALUES (?)");
statement.setBinaryStream(1, input);
statement.executeUpdate();
A PreparedStatement
is really useful. It not only saves you from SQL injections, but it also eases setting fullworthy Java objects like InputStream
in a SQL statement. You can learn more about PreparedStatement
at the JDBC tutorial.
Well what I do to store binary data such as images, is quite simplictic. In my case I deal with uploaded files which get posted to a servlet. Inside the servlet, I get the InputStream on the posted body with request.getInputStream(). However, this works with any kind of InputStreawm, inlcuding one based on an URL. The sample code below shows how to convert that InputStream into google appeninge Blob, which then you can for instance make persistant in the data store.
...
import org.apache.commons.io.IOUtils;
import com.google.appengine.api.datastore.Blob;
...
public void InputStreamToBlob(InputStream i) throws IOException {
...
Blob content = new Blob(IOUtils.toByteArray(i));
...
For an image, instead of reading the buffer line by line, you'll load it in byte array, and save this byte array as a blob.
精彩评论