gpt4 book ai didi

c# - 无法访问在后端项目中上传的图片

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:49 26 4
gpt4 key购买 nike

我正在尝试访问存储在我的前端应用程序的/uploads/文件夹中的图像。

http://localhost:4200/uploads/a.jpg 我都得到了 404和 http://localhost:4200/StaticFiles/a.jpg .我需要图像的路径才能在图库中显示它。

我尝试使用图像的完整路径(“D:/blabla/uploads/a.jpg”),但似乎受到限制。然后我使用下面的代码从后端提供到我的上传文件夹的路径,但我仍然得到 404。

我的后端和前端项目在不同的文件夹中,我的前端向后端的端口发送请求。

后端运行最新的 .net 核心,前端是 Angular 8。

这是我提供静态文件的方式:

var aux = Path.Combine(Directory.GetCurrentDirectory(), "uploads");

app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(aux),
RequestPath = "/StaticFiles"
}
);

这就是我上传图片的方式。该代码在项目内的/uploads 文件夹中工作并上传图像。

var uploadFilesPath = Path.Combine(_host.ContentRootPath, "uploads");

if (!Directory.Exists(uploadFilesPath))
Directory.CreateDirectory(uploadFilesPath);

foreach (var file in fileData)
{
var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadFilesPath, fileName);

using (var stream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(stream);
}

var propToAddImageTo = _propManager.GetById(id);

_propManager.AddImage(propToAddImageTo, filePath);
}

当我尝试设置一个简单的 <img src="localhost:4200/uploads/a.jpg"><img src="localhost:4200/StaticFiles/a.jpg"> ,Mozilla 开发人员工具的网络选项卡上的请求显示 404。

最佳答案

_host.ContentRootPath 的默认值等于 Directory.GetCurrentDirectory(),但前提是您使用 WebHost.CreateDefaultBuilder。来自documentation :

CreateDefaultBuilder performs the following tasks:

  • ...

  • Sets the content root to the path returned by Directory.GetCurrentDirectory.

您的代码假定 ContentRootPath 始终Directory.GetCurrentDirectory 相同,但这并不总是正确的。如果您没有使用 CreateDefaultBuilder,或者您的代码分布在多个项目中(正如您在评论中提到的),它们将不会指向同一个地方。

关于c# - 无法访问在后端项目中上传的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655762/

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