如何在Java Rest API中获取真实路径InputStream文件

2020年1月4日 18点热度 0条评论

我有一个Java Rest API Post方法,可以将图像(InputStream)作为参数发送,并且必须将其保存在Oracle的blob列中。

我需要获取此InputStream的完整路径(真实路径)以将此图像保存在数据库中。
我的代码如下。

@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

我想做这样的事情:

String UPLOAD_FOLDER = uploadedInputStream.getRealPathName();

要么

String UPLOAD_FOLDER = fileDetail.getRealPathName();

解决方案如下:

我通过将输入流转换为字节数组解决了该问题。我将byte []转发到了数据库持久性方法。我的代码如下:

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