首页 > 解决方案 > 如何从.net核心API和数据库显示图像角度

问题描述

我想显示一张图片,它的路径存储在数据库中

这就是它将图像文件传输到数据库的方式。

        public string UploadImage(IFormFile file)
        {
            if (file == null) throw new Exception("Pusty plik");
            if (file.Length == 0)
            {
                throw new Exception("Pusty plik");
            }
            if (!ACCEPTED_FILE_TYPES.Any(s => s == Path.GetExtension(file.FileName).ToLower())) throw new Exception("Zły typ pliku");

            if (string.IsNullOrWhiteSpace(host.WebRootPath))
            {
                host.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            }
            var uploadFilesPath = Path.Combine(host.WebRootPath, "images");
            if (!Directory.Exists(uploadFilesPath))
                Directory.CreateDirectory(uploadFilesPath);
            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadFilesPath, fileName);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyToAsync(stream);
            }
            var path = Path.Combine(Directory.GetCurrentDirectory(), @"/wwwroot/images/", fileName);

            return path;
        }

这里存储文件: https ://zapodaj.net/a8829a7a3a90b.png.html

标签: c#.netangulardatabase

解决方案


在您的示例代码中,我没有看到从数据库返回的路径。

同样从安全的角度来看,返回/wwwroot/images/响应也是不好的做法。您可以在共享位置上创建一个文件夹并返回共享位置路径。

似乎您有疑问,并且相同的代码没有对齐。


推荐阅读