如何从Postgresql数据库返回图像。我应该将其渲染为图像吗?我正在使用.Net Core Web API

时间:2018-11-06 11:38:46

标签: .net postgresql rest core

我正在使用.Net Core Web API将Web API Rest服务创建为微服务,以将图像上传到PostgreSQL数据库。而且我想创建一个get操作以按ID返回图像,我真的不知道该怎么办,所以请您提供任何帮助,至少我需要一些指南。

这是我的课程

     namespace Upload_images_API.Models
     {
       public class Image
       {
             public int ImageId { get; set; }
             public byte[] ImageData { get; set; }


      }
    }

这是我发布图片的控制器。

public class ImageController : ControllerBase
{
    private readonly ImageDbContext _context;
    public ImageController(ImageDbContext context)
    {
        _context = context;
    }
    [HttpPost("api/Image/upload")]
    public async Task<IActionResult> UploadImage(Image images, List<IFormFile> ImageData)
    {

        if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

        foreach (var item in ImageData)
        {

            if (item.Length > 0)
            {
                using (var stream = new MemoryStream())
                {
                   await item.CopyToAsync(stream);
                    images.ImageData = stream.ToArray();
                }
            }
        }

        if (images.ImageData == null)
        {
            return BadRequest("Image should be selected.");
        }

        _context.Image.Add(images);
        _context.SaveChanges();

        int imageid = images.ImageId;

        return Ok("Image ID:" + imageid);
    }

请提供任何帮助,非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以创建一个表,该表的列类型为bytea。 在模型中,您可以将数据存储在byte []字段中。

我正在使用dapper框架在数据库中读写:

    public static bool savePhoto(PhotoModel input, IDbConnection connection)
    {

        string sql = "insert into photo(id, photo, notes) VALUES (@Id, @photo, @notes)";
        int res = connection.Execute(sql,new { Id = input.Id, photo = input.photo, notes = input.notes});

        if (res == 1)
        {
            return true;
        } else
        {
            return false;
        }

    }


    public static List<PhotoModel> readPhotosById(Int64 id)
    {
        using (IDbConnection connection = DBConnection.ConnectionFactory())
        {
            string sql = "select id, photo, notes from photo where id = @idPhoto";
            connection.Open();
            List<PhotoModel> photos = connection.Query<PhotoModel>(sql, new { idPhoto = id }).AsList<PhotoModel>();

            return photos;
        }
    }