I created a api to upload image and a api to get image by Resource (FTP-server and spring boot). In front-end, i use reactjs and display image by base64. but some image i was upload cannot be displayed (mainly .png). when i take blob of response that image and convert to base64 then convert to images but it not be displayed.
upload:
- Ftp Store:
@Override
public boolean storeFile(String filePath, InputStream fileIs) {
FileStoreConnectInfo connectInfo = new FileStoreConnectInfo(appProperties);
try (FtpService ftpService = new FtpService(connectInfo)) {
return ftpService.store(filePath, fileIs);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
get image by Resource:
- Controller:
@GetMapping("/me/profile/avatar/download")
public ResponseEntity<Resource> download(@RequestParam String path){
ImageResponse response = userProfileService.download(path);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(response.getResource());
}
- ImageResponse:
@Getter @Setter
public class ImageResponse {
private Resource resource;
public ImageResponse() {}
}
- Implement:
public ImageResponse download(String avatarUrl) {
InputStream fis = userProfileStoreService.getFile(path + avatarUrl);
InputStreamResource resource = new InputStreamResource(fis);
ImageResponse response = new ImageResponse();
response.setResource(resource);
return response;
}
- FTP get file:
FileStoreConnectInfo connectInfo = new FileStoreConnectInfo(appProperties);
try (FtpService ftpService = new FtpService(connectInfo)) {
return ftpService.retrieveFileStream(filePath);
} catch (Exception e) {
throw new RuntimeException(e);
}