我有一个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();
...
}