0

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();
  • Most browsers don't send the full original file path of the file they upload any more (for security/privacy reasons). They'll only send the file name without the path. Why would you need that? – Joachim Sauer Sep 30 '19 at 14:46
  • This `InputStream` is most likely not a `FileInputStream`, and is most likely not associated with a file. This SO post will help you understand how to write an InputStream to a BLOB column in Oracle: https://stackoverflow.com/questions/8348427/how-to-write-update-oracle-blob-in-a-reliable-way – StvnBrkdll Sep 30 '19 at 14:47
  • This post method will receive an image through an android app. I need to write this file to the database. File handling methods (new File("path/filename.jpg"), new FileInputStream("path/filename.jpg"), etc...) ask for full path – Gustavo de Freitas Sep 30 '19 at 16:12

1 Answers1

0

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();
    ...
}