Reputation: 69
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?
Upvotes: 0
Views: 1693
Reputation: 338
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();
}
}
Upvotes: 2