问题描述
我在共享的 Windows 服务器上托管,我想在服务器上保存图像,并更新其在数据库中的路径。当我更新数据库中的路径时,它看起来像下面提到的,
C:\ClientSites\mydomain.com\mydomain.com\pictures\20210330160946.png
如何使用正确的 URL 进行保存,以便使用完整的 URL 来显示图像?
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(),@_configuration.GetSection("pictures").Value);
var file = Request.Form.Files[0];
if (file.Length > 0)
{
var user = dbContext.User.GetById(1000);
var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}";
var fullPath = Path.Combine(pathToSave,fileName);
using (var stream = new FileStream(fullPath,FileMode.Create))
{
file.copyTo(stream);
}
user.ProfilePhotoUrl = fullPath;
var result = dbContext.User.Update(user);
if (result.Succeeded)
{
return Json(fullPath);
}
}
解决方法
为了提供静态文件,您可以使用 NuGet Microsoft.AspNetCore.StaticFiles 并在 startup.cs 配置方法中设置其中间件:
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\your\path\with\pictures"),RequestPath = new PathString("/pictures")
});
这样,就不需要保存图像的整个路径,只需要保存它的名称。您只需将上传时的图片放入“D:\your\path\with\pictures”,然后就可以在“/picture”路径上访问它们。
为了形象化,让我给你下面的解释。假设我的应用程序在 localhost:24757 上。如果我在“D:\your\path\with\pictures”中有一个名为 some-picture.jpg 的文件,我可以在这个 URL 上显示它: localhost:24757/pictures/some-picture.jpg