0

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);
        }

Nguyễn VŨ
  • 161
  • 2
  • 6
  • `MediaType.APPLICATION_OCTET_STREAM` looks wrong. Have you tried replacing it with the actual content type of the image (e.g. "image/png" or "image/jpeg" or their constants from `MediaType`? – Alexander Jan 13 '20 at 10:10
  • I don't really understand this much yet, is changing this really good when I want to return multiple types of images (png, jpg, gif, ....) ? – Nguyễn VŨ Jan 13 '20 at 10:26
  • I have just tried but it not working – Nguyễn VŨ Jan 13 '20 at 10:30

0 Answers0