ASP.NET Core MVC, Get file from database, and render as image

后端 未结 2 412
说谎
说谎 2021-01-05 16:05

I have image data being stored in a SQL table with a field type of varbinary(max) I also store the image content type.

Using Microsoft ASP.NET Core MVC an

2条回答
  •  遥遥无期
    2021-01-05 16:53

    The below code is just off the top of my head, so it might need some tweaks, but it will give you the basic idea.

    Create a new controller and put your methods in there:

    public ImageController : Controller
    {
        public FileStreamResult GetFile(string FileID)
        {
            return GetFile(new Guid(FileID));
        }
    
        public FileStreamResult GetFile(Guid FileID)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                DynamicParameters dynamicParameters = new DynamicParameters();
                dynamicParameters.Add(@"ID", FileID);
                FileModel result = connection.Query("GetFile", dynamicParameters, commandType: CommandType.StoredProcedure).FirstOrDefault();
                Stream stream = new MemoryStream(result.FileData);
                return new FileStreamResult(stream, result.FileType);
            }
        }
    }
    

    then in your markup, reference the controller:

    
    

提交回复
热议问题