我现在有一个Web服务,它从前端获取图像并将其保存为数据库中的BLOB。我想从数据库中获取图像并将其重新发送回前端并在那里显示图像。
我该如何解决?
这是我的模特:
@Entity
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Lob
private byte[] image;
public Document(){}
public Document(byte[] image) {
this.image = image;
}
这是服务:
@Service
public class DocumentServiceImpl implements DocumentService {
private DocumentRepository documentRepository;
@Autowired
public DocumentServiceImpl(DocumentRepository documentRepository) {
this.documentRepository = documentRepository;
}
@Override
public void saveDocument(Document document) {
documentRepository.save(document);
}
@Override
public List<Document> getAllDocuments() {
return documentRepository.findAll();
}
@Override
public void deleteDocument(Integer id) {
documentRepository.delete(id);
}
@Override
public Document getById(Integer id) {
return documentRepository.getOne(id);
}
这是控制器:
@Controller
public class DocumentController {
private DocumentService documentService;
public DocumentController(DocumentService documentService) {
this.documentService = documentService;
}
@RequestMapping(value="/upload", method= RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> saveNewDocument(@RequestParam("file")MultipartFile file, HttpServletRequest httpServletRequest){
if (file.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Please select a file to upload.");
}
try {
byte[] bytes = file.getBytes();
Document document = new Document();
document.setImage(bytes);
documentService.saveDocument(document);
return ResponseEntity.status(HttpStatus.OK).body("File uploaded succesfully");
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File could not be uploaded");
}
}
前端:
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>FileUpload</title>
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
&#13;
答案 0 :(得分:1)
我猜你可以这样做:
<强>控制器:强>
@RestController
@RequestMapping("/image")
public class ImageController {
@RequestMapping(value = "{imageId}", method = RequestMethod.GET)
public ResponseEntity getImage(@PathVariable("imageId") Long imageId) {
Document doc = documentService.findOne(imageId);
if (doc == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, "image/*").body(doc.getImage());
}
}
<强> HTML:强>
...
<img src="/image/{imageId}">
...