gpt4 book ai didi

spring-boot - Spring Boot : The image is not displayed in the browser, 我有一个 404 错误

转载 作者:行者123 更新时间:2023-12-05 05:47:55 27 4
gpt4 key购买 nike

大家好,我正在学习 spring boot,我一直在学习一些教程,我一直在浏览器中显示图像,我已经设法将它保存在名为“user-photos”的路径中但它不保存内部资源,而是作为一个单独的文件夹,当我尝试在浏览器中显示它时,出现 404 错误。

这是我用来保存带有图像的用户的 Controller :

@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";
}

现在我创建了我的 MVC Controller ,允许显示名为 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 + "/");

}
}

最后,我创建了一个 img 标签以使用以下代码片段显示它:

<img th:if="${user.photos != null}" th:src="@{${user.photosImagePath}}" >

最佳答案

如果还没有解决,需要去掉controller中的“ShopmeWebParent/ShopmeBackEnd/”,只留下“user-photos + ...”

关于spring-boot - Spring Boot : The image is not displayed in the browser, 我有一个 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70911292/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com