Spring Boot视频上传后播放404问题:无需重启服务器的解决方法
解决Spring Boot视频上传后播放404无需重启的问题
核心原因
上传的视频文件未被Spring Boot静态资源处理器实时识别——默认情况下Spring Boot启动时仅扫描指定静态目录,后续新增的文件不会自动纳入映射范围,导致直接访问返回404,重启后服务器重新扫描目录才能识别文件。
解决方案
1. 配置动态资源映射
创建WebMvc配置类,手动注册资源处理器,指定上传目录的绝对路径并禁用缓存,确保每次请求都读取实际文件:
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 WebMvcConfig implements WebMvcConfigurer { // 替换为你的视频上传绝对路径,例如Linux/macOS用"file:/home/user/upload/videos/",Windows用"file:D:/upload/videos/" private static final String VIDEO_UPLOAD_PATH = "file:/your/absolute/upload/path/"; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 前端通过/videos/**路径访问上传的视频 registry.addResourceHandler("/videos/**") .addResourceLocations(VIDEO_UPLOAD_PATH) .setCachePeriod(0); // 禁用缓存,实时读取最新文件 } }
2. 校验上传路径一致性
确保文件上传代码的保存路径和上述配置的VIDEO_UPLOAD_PATH完全一致,示例上传逻辑:
String uploadDir = "/your/absolute/upload/path/"; File destFile = new File(uploadDir + uploadedFileName); // 执行文件写入操作 file.transferTo(destFile);
3. 排查开发环境缓存问题
- 检查IntelliJ是否将上传目录标记为"Excluded":右键上传目录 → Mark Directory as → Not Excluded
- 清理IDE缓存:File → Invalidate Caches... → 勾选Clear file system cache and local history → 重启IDE(解决IDE层面的文件读取缓存问题)
4. Actuator刷新方案(可选)
若需通过接口触发资源刷新,补充以下配置:
- 在
application.properties中开启刷新端点:
management.endpoints.web.exposure.include=refresh management.endpoint.refresh.enabled=true
- 在WebMvc配置类上添加
@RefreshScope注解,之后调用POST /actuator/refresh接口即可手动刷新资源映射(此方案不如动态映射直接,适合特殊场景)
验证步骤
- 上传新视频,确认文件成功写入配置的上传目录
- 直接通过浏览器访问映射路径(如
http://localhost:8080/videos/test.mp4),验证是否能正常播放
内容的提问来源于stack exchange,提问作者Helouss Mystery
相关产品推荐
相关产品推荐

