Spring Boot & React, Image Upload & Display

박진석·2025년 2월 13일
0

FindMyBMW

목록 보기
9/10

How do we serve static files in Spring Boot and display the image in React?
Recently, I faced a challenge while working on a Spring Boot application. I needed to upload images and serve them as static files so they could be accessed from the frontend. Initially, I encountered a 403 Forbidden error when trying to access the uploaded images. After some investigation and configuration tweaks, I finally got it working. Here's how I did it.

The Problem

I was storing uploaded images in the uploads directory located at

C:/Users/jjpar/career/backend (3)/uploads/

However, when I tried to access these images from the frontend using a URL like

 http://localhost:8080/uploads/[image name]

I kept getting a 403 Forbidden error.

The Solution

To resolve this issue, I needed to configure my Spring Boot application to serve static files from the uploads directory and ensure that the security settings allowed access to these files.

Step 1: Configure Resource Handlers

First, I updated the SecurityConfig.java file to include a resource handler for the uploads directory. This configuration tells Spring Boot to serve static files from the specified directory.
SecurityConfig.java

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // Ensure CORS is enabled
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/**", "/uploads/**").permitAll() // Allow access to uploads
                        .anyRequest().authenticated()
                )
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:C:/Users/jjpar/career/backend (3)/uploads/");
    }

Step 2: Allow Access to Static Files

Next, I ensured that the security configuration allowed access to the uploads directory. This was done by updating the authorizeHttpRequests method to permit all requests to

/uploads/**.

Step 3: Update the Frontend

Finally, I updated the frontend code to correctly fetch and display the images associated with the reviews. The src attribute of the img tag was updated to use the correct URL path for the uploaded files.

FullReview.js

               {mediaList.map((media, index) => (
                  <img 
                    key={index} 
                    src={`http://localhost:8080/uploads/${media.fileName}`} 
                    alt={media.fileName} 
                    className="review-photo" 
                  />
                ))}

Conclusion

By configuring the (1) resource handlers and (2) updating the security settings, I was able to successfully serve static files from the uploads directory and display them in the frontend. This approach ensures that the images are accessible and properly displayed.

0개의 댓글