2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
在保存之前,您可以在 Rest Service 中將圖像 url 轉(zhuǎn)換為數(shù)據(jù)字節(jié) [] 圖像。
public static byte[] convertImageByte(URL url) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
return byteChunk;
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
return null;
}

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
好的問(wèn)題解決了。將圖像 URL 轉(zhuǎn)換為字節(jié)數(shù)組的代碼如下。有關(guān)此問(wèn)題的更多答案,請(qǐng)參閱此處
public static byte[] convertImageByte(URL url) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = new BufferedInputStream(url.openStream());
byte[] byteChunk = new byte[4096];
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
return baos.toByteArray();
}
catch (IOException e) {e.printStackTrace ();}
finally {
if (is != null) { is.close(); }
}
return null;
}
將 Dto 保存到數(shù)據(jù)庫(kù)時(shí)
if(dto.getImageUrl() != null) {
try {
URL imageUrl = new URL(dto.getImageUrl());
itemDO.setImage(convertImageByte(imageUrl));
} catch (IOException e) {
e.printStackTrace();
}
}
entity = orderItemRepository.save(itemDO);
從數(shù)據(jù)庫(kù)中獲取圖像
public byte[] getImageForOrderItem(long itemId) {
Optional<OrderItemDO> option = orderItemRepository.findById(itemId);
if(option.isPresent()) {
OrderItemDO itemDO = option.get();
if(itemDO.getImage() != null) {
byte[] image = itemDO.getImage();
return image;
}
}
return null;
}
通過(guò) Rest API 調(diào)用 Image Response
@GetMapping(path="/orderItem/image/{itemId}")
@ResponseStatus(HttpStatus.OK)
public void getImageForOrderItem(@PathVariable("itemId") long itemId, HttpServletResponse response) {
byte[] buffer = orderServiceImpl.getImageForOrderItem(itemId);
if (buffer != null) {
response.setContentType("image/jpeg");
try {
response.getOutputStream().write(buffer);
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
添加回答
舉報(bào)