Spring boot URL로 access되지 않는 이미지 웹으로 전달하기

2024. 12. 5. 18:33Java/Spring Boot

Spring boot

import org.springframework.core.io.Resource

@RestController
@RequestMapping("/images")
public class ImageController {

    @GetMapping("/{imageName}")
    public ResponseEntity<Resource> getImage(@PathVariable String imageName) throws IOException {
        Path imagePath = Paths.get("/path/to/your/private/images/" + imageName);
        Resource resource = new UrlResource(imagePath.toUri());

        if (!resource.exists() || !resource.isReadable()) {
            throw new RuntimeException("Image not found: " + imageName);
        }

        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG) // Adjust for your image type
                .body(resource);
    }
}

Sencha

Ext.application({
    name: 'ImageApp',

    launch: function () {
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [
                {
                    xtype: 'panel',
                    title: 'Image Display',
                    items: [
                        {
                            xtype: 'image',
                            src: '/images/your-image-name.jpg', // Endpoint from the backend
                            alt: 'Example Image',
                            style: {
                                width: '100%',
                                height: 'auto'
                            }
                        }
                    ]
                }
            ]
        });
    }
});