Reputation: 73
Hello everyone I'm learning spring boot and well I've been following some tutorials and well I'm stuck showing the image in the browser, I've already managed to save it in the path called "user-photos" but it doesn't save inside resources but as a separate folder, when I try to show it in the browser I get a 404 error.
This is my controller that I used to save an user with the image:
@PostMapping("/users/save")
public String saveUser(User user,
RedirectAttributes redirectAttributes,
@RequestParam("image")MultipartFile multipartFile) throws IOException {
if (!multipartFile.isEmpty()) {
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
user.setPhotos(fileName);
User savedUser = userService.save(user);
String uploadDir = "ShopmeWebParent/ShopmeBackEnd/user-photos/" + savedUser.getId();
FileUploadUtil.saveFile(uploadDir, fileName, multipartFile);
}
// userService.save(user);
redirectAttributes.addFlashAttribute("message", "The user has been saved successfully.");
return "redirect:/users";
}
Now I created my MVC Controller to be allowed to show images called MvcConfig:
package com.shopme.admin;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.file.Path;
import java.nio.file.Paths;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String dirName = "user-photos";
Path userPhotosDir = Paths.get(dirName);
String userPhotosPath = userPhotosDir.toFile().getAbsolutePath();
registry.addResourceHandler("/user-photos/**")
.addResourceLocations("file:/" + userPhotosPath + "/");
}
}
Finally I created an img tag to show it with the followind code snippet:
<img th:if="${user.photos != null}" th:src="@{${user.photosImagePath}}" >
Upvotes: 3
Views: 593
Reputation: 26
if you haven't solve it, you need to remove the in the controller "ShopmeWebParent/ShopmeBackEnd/" only leave the "user-photos + ..."
Upvotes: 1