![](/img/trans.png)
[英]Java return Inputstream via rest API with html file in inputstream
[英]How to get real path InputStream file in Java Rest API
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.
我需要獲取此 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();
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.