Spring boot 이미지 Map으로 전달하기

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

Spring boot

@RestController
@RequestMapping("/api")
public class ResourceController {

    @GetMapping("/resource-with-map")
    public ResponseEntity<Map<String, Object>> getResourceWithMap() throws IOException {
        // Load the resource (example: an image)
        Path imagePath = Paths.get("/path/to/your/image.jpg");
        Resource resource = new UrlResource(imagePath.toUri());

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

        // Create a Map to hold the response data
        Map<String, Object> response = new HashMap<>();
        response.put("name", "Sample Image");
        response.put("description", "This is an example image resource.");
        response.put("resource", resource);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(response);
    }
}

Sencha

Ext.application({
    name: 'ResourceApp',

    launch: function () {
        // Make an AJAX request to fetch the Map data from the backend
        Ext.Ajax.request({
            url: '/api/resource-with-map', // Endpoint from Spring Boot
            method: 'GET',
            success: function (response) {
                // Parse the response
                const data = Ext.decode(response.responseText);

                // Create a panel to display the data
                Ext.create('Ext.container.Viewport', {
                    layout: 'vbox',
                    items: [
                        {
                            xtype: 'panel',
                            title: data.name,
                            html: `<p>${data.description}</p>`,
                            padding: 10
                        },
                        {
                            xtype: 'image',
                            src: data.resource, // Use the resource path for the image
                            alt: data.name,
                            style: {
                                width: '100%',
                                height: 'auto'
                            }
                        }
                    ]
                });
            },
            failure: function (response) {
                Ext.Msg.alert('Error', 'Failed to load resource data.');
            }
        });
    }
});