You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新上传图片返回404错误、重启网站后可正常加载问题排查求助

问题根因及解决方案

核心根因

你当前将用户上传的图片存储到了ClientApp/src/assets目录,该目录是Angular的编译时静态资源目录:

  • 开发模式下ng serve仅会在服务启动时扫描一次该目录下的资源,运行时新增的文件不会被动态识别,因此重启前访问会返回404
  • 生产环境打包后src目录会被编译销毁,该存储路径完全不可用

其他已知问题

  1. 路径拼接不规范:前端代码用反斜杠\拼接路径,跨平台(Linux/macOS)下无法正常识别
  2. 异步写法错误:ngOnInit中对Observable返回的subscribe方法使用await,属于无效写法,无实际作用

修复步骤

1. 调整文件存储路径

在项目根目录新建独立的上传文件存储目录,例如Uploads/PhotoGallery,专门用于存储用户上传的资源,不要和Angular编译目录混用。

2. 配置ASP.NET Core静态文件映射

在Startup.cs(.NET 6+则是Program.cs)的配置管道中新增静态文件规则,将上传目录映射到对应的请求路径:

// 需先引入命名空间 using Microsoft.Extensions.FileProviders;
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Uploads", "PhotoGallery")),
    RequestPath = "/assets/PhotoGallery"
});

该配置会将所有/assets/PhotoGallery/xxx的请求直接映射到本地Uploads/PhotoGallery目录下的对应文件,运行时新增的文件可直接访问。

3. 修改Controller路径配置

更新imageUploadController的构造函数中的存储路径:

public imageUploadController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
    SetFullPath(Path.Combine(_hostingEnvironment.ContentRootPath, "Uploads", "PhotoGallery"));
}

4. 修复前端路径拼接逻辑

修改photos.component.ts中的setPhotos方法,统一使用正斜杠拼接绝对路径:

setPhotos(newArray: any[]) {
  newArray.forEach(path => {
    // 直接使用绝对路径,无需拼接../
    this.photos.push("/" + path.trim().replace(/\\/g, '/'))
  });
}

同时删除ngOnInit中无效的async、await关键字:

ngOnInit() {
  this.http.get<any[]>(this.baseUrl + 'api/imageUpload').subscribe(result => {
    this.catcher = result;
    this.setPhotos(result);
    console.log(result);
  }, error => console.error(error));
}

内容的提问来源于stack exchange,提问作者Derek S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:06:04