开发者

How can I use one stream and save result to many places?

I 开发者_运维百科using servlet and Apache ServletFileUpload that provides stream to uploaded image. All I want to do is to store that image to db and also store resized (I using JAI) version to db.

How can I achieve this without saving image to drive. As I understand stream can be read only once. So I need to store whole image in memory? Is it expensive for performance? Or there are another way?


As I understand stream can be read only once.

Yes

So I need to store whole image in memory?

Probably, but not necessarily. Look at setBinaryStream method of PreparedStatement. Under some conditions you could probably just pass your input stream to that method. Look at some other stream method, your JDBC driver may only support a subset of those.

With some clever bufferization you may probably serve original stream and resized image as well in a single call.

Is it expensive for performance?

What performance you are talking about. If memory is limited this of course going to matter. Otherwise memory I/O is the least probable place to become a bottleneck.

If you have enough memory, I would recommend you to take this approach, as the implementation is the most straight forward and memory is cheap.

Or there are another way?

As I said before, you may create a clever bufferization technique, but this requires a lot of testing ( and designing ). If memory is limited, you may have to revert to this approach, otherwise, just read the whole stream in, process it and write the result to the DB.


This is how you could get a byte array from the input stream. You should be concerned with running out of memory if the stream is too large.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class SO2805548
{
  public static byte[] getStreamData(InputStream is) throws IOException
  {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int i = -1;
    while ((i = is.read()) != -1)
    {
      os.write(i);
    }
    return os.toByteArray();
  }

  public static void main(String[] args) throws IOException
  {
    byte[] input = "foobar".getBytes("UTF-8");
    ByteArrayInputStream inputStream = new ByteArrayInputStream(input);

    byte[] data = getStreamData(inputStream);

    System.out.println("arrays are equal = " + Arrays.equals(input, data));
  }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜