I have a Java Rest API Post method that sends an image (InputStream) as a parameter, and I have to save it in a blob column in Oracle.
I need to get the full path (real path) of this InputStream to save this image in database. My code is below.
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
String UPLOAD_FOLDER = "c:/uploadedFiles/"; // my rest api does not have this file, how to get at runtime?
String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName(); // this line is ok
I would like to do something like this:
String UPLOAD_FOLDER = uploadedInputStream.getRealPathName();
or
String UPLOAD_FOLDER = fileDetail.getRealPathName();
I solved the problem by converting the inputstream to byte array. I forwarded the byte[] to the database persistence method. My code is below:
public byte[] toByteArray(InputStream is) throws IOException{
ByteArrayOutputStream baus = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len= is.read(buffer)) != -1){
baus.write(buffer, 0, len);
}
return baus.toByteArray();
}
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
...
byte[] b = toByteArray(uploadedInputStream);
business.saveUploadedFileInDatabase(b);
...
}
public boolean uploadFile(byte[] b) throws SQLException, IOException{
...
PreparedStatement ps = conn.prepareStatement("INSERT INTO TABLE_IMAGE_TEST (CODE, IMAGE) VALUES (?, ?)");
pstmt.setLong(1, 1L);
pstmt.setBytes(2, b);
pstmt.execute();
...
}