0

I want to implement a Java program where a client will be able to upload a file(image, text etc) from the client side and it being sent to the server side where the file will be stored in a folder on the server computer.

Is this possible and realistic? Is EJB a better way of doing this? Are there any good resources available?

Cœur
  • 37,241
  • 25
  • 195
  • 267
abcdefg
  • 69
  • 9

1 Answers1

2

You can create a class in a common package as follows, then call createByteArray() from client-side and convert image into a byte array. Then pass it into a skeleton and reconstruct an image using createBufferedImage(). Finally, save it as a JPEG using toFile():

/**
 *
 * @author Randula
 */
public class TransportableImage {
/**
 * 
 * @param bufferedImage
 * @return
 * @throws IOException 
 */
    public byte[] createByteArray(BufferedImage bufferedImage) 
            throws IOException {

        byte[] imageBytes = null;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        JPEGImageEncoder jpg = JPEGCodec.createJPEGEncoder(bos);
        jpg.encode(bufferedImage);
        bos.flush();
        imageBytes = bos.toByteArray();
        bos.close();
        return imageBytes;
    }
//Reconstruct the BufferedImage

    public BufferedImage createBufferedImage(byte[] imageBytes) 
            throws IOException {

        InputStream is = new ByteArrayInputStream(imageBytes);
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
        BufferedImage image = decoder.decodeAsBufferedImage();
        is.close();
        return image;
    }
//Save a JPEG image

    public void toFile(File file, byte[] imageBytes) 
            throws IOException {

        FileOutputStream os = new FileOutputStream(file);
        os.write(imageBytes, 0, imageBytes.length);
        os.flush();
        os.close();
    }

}
Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Randula Koralage
  • 328
  • 2
  • 10
  • The question is how to do it in RMI, and you haven't answered it. – user207421 Feb 24 '21 at 03:35
  • Well, RMI supports transfer of `byte[]` data, so the rest relates to just generalized transfer of objects via RMI. But you are right, this could be added to the answer. – Koenigsberg Sep 23 '21 at 14:06