I’m trying to send a request
<body>
<div class="container">
<div class="form">
<header>Add New Image</header>
<form id="image-form" enctype="multipart/form-data">
<div class="field">
<input type="text" id="image-title" name="title" placeholder="Enter image title" required>
</div>
<div class="field">
<textarea id="image-description" name="description" placeholder="Enter image description" required></textarea>
</div>
<div class="field">
<input type="file" id="image-file" name="image" accept="image/*" required>
<label for="image-file">Choose Image</label>
<div class="file-name" id="file-name">No file chosen</div>
</div>
<div class="field">
<button type="button" onclick="uploadImage()">Upload Image</button>
</div>
</form>
</div>
</div>
<script>
const fileInput = document.getElementById('image-file');
const fileNameDisplay = document.getElementById('file-name');
fileInput.addEventListener('change', function() {
if (fileInput.files.length > 0) {
fileNameDisplay.textContent = fileInput.files[0].name;
} else {
fileNameDisplay.textContent = 'No file chosen';
}
});
function uploadImage() {
const form = document.getElementById('image-form');
const formData = new FormData(form);
fetch('/api/images/upload', {
method: 'POST',
body: formData,
})
.then(response => response.text())
.then(data => {
console.log(data);
alert('Image uploaded successfully!');
})
.catch(error => {
console.error('Error:', error);
alert('Failed to upload image.');
});
}
</script>
</body>
To a Spring Boot server:
@RestController
@RequestMapping("/api/images")
public class ImageAPI {
private final ImageService imageService;
public ImageAPI(ImageService imageService) {
this.imageService = imageService;
}
@PostMapping("/upload")
public ResponseEntity<String> upload(
@RequestParam("title") String title,
@RequestParam("description") String description,
@RequestParam("image") MultipartFile image) {
System.out.println("/upload");
try {
imageService.uploadImage(title, description, image);
return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, "/home").build();
} catch (Exception e) {
return ResponseEntity.status(500).body("Error uploading image: " + e.getMessage());
}
}
}
But I get next notification on Spring console:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method ‘POST’ is not supported]
To check that controller is working I added this System.out.println("/upload");
– and I don’t see this in my console. So, controller is not firing
I think the problem may be in the security configuration settings:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Autowired
CustomUserDetailService userDetailService;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(registry -> {
registry.requestMatchers("/registration", "/static/**", "/api/**").permitAll();
registry.anyRequest().authenticated();
})
.formLogin((form) -> form
.loginPage("/login")
.defaultSuccessUrl("/home", true)
.permitAll()
)
.build();
}
@Bean
public UserDetailsService userDetailsService() {
return userDetailService;
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
As you can see I turned off CSRF and added /api/**
to always permitted requests, but it all doesn’t help me at all.
That is what I see in the Chrome console:
P.S. I use Spring Boot version 3.3.2.
6