映像无法从外部文件夹加载,Spring 启动



员工应该能够上传他们的个人资料图片,并且该个人资料图片应该显示在employee_info页面中。我正在学习本教程:https://www.youtube.com/watch?v=-Xf_fbKQit8上传图片正在工作,但我无法将图片带到网页。

我的照片在Spring Boot项目之外的一个文件夹中。我尝试过这种配置:

如何";显示";来自外部文件夹的文件与spring-boot 2.1.1

实现WebMvcConfigurer:的ConfigMVC类

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer
{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{   
String employeeProfileUploadPath = "file:C:/my_company/profile_pictures/";

registry.addResourceHandler("/images/**").addResourceLocations(employeeProfileUploadPath);
}

就像在视频教程中一样,我通过DTO类中的方法为员工传递图像的URL:

@Transient
public String getPhotoImagePath()
{
if(photo == null || nickname == null)
return null;

return "/my_company/profile_pictures/" + nickname + "/" + photo;
}

在控制器中,我将EmployeeDTO类型的对象传递给模型:

MyCompanyUserDetails userDetails = (MyCompanyUserDetails)principal;
int employeeId = userDetails.getEmployeeId();
Optional<EmployeeDTO> optional = employeeRepository.findById(employeeId);
EmployeeDTO employeeDTO = optional.get();
model.addAttribute("employeeDTO", employeeDTO);

在html中使用Thymelaf:

<img th:src="@{${employeeDTO.photoImagePath}}" width = "180" height = "180">

Thymelaf放置的URL:

http://localhost:8080/my_company/profile_pictures/admin1/admin1.jpg

这是我的图像在电脑中的正确位置。我不想把它存储在/static/images/**在Spring Boot项目中,我想要这种方式,并且我已经完成了MVC配置,正如您在上面看到的那样。我不知道问题出在哪里,但在谷歌Chrome控制台上,我收到了404错误,找不到资源。

您使用的URL不正确。路径应该类似于:

http://localhost:8080/{appname}/images/admin1/admin1.jpg

添加到您的application.properties

spring.resources.static-locations = classpath:/static/,file:///C:/my_company/profile_pictures/

假设您的文件名是user.jpg,并放入此位置C:\my_company/profile_pictures/

因此您可以通过调用http://localhost:8080/user.jpg直接访问

最后,您可以根据base path and directory as well as file name自定义您的路径或URL

最新更新