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

后端 未结 2 404
说谎
说谎 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<FileModel>("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:

    <img src="@Url.Action("GetFile", "Image", new {FileId = content.FileID})" />
    
    0 讨论(0)
  • 2021-01-05 17:07

    As @fileExtensions.GetFile(content.FileID) actually returns an FileStreamResult it wouldn't be able to render it inside html and probably just returns FileStreamResult.ToString().

    Check rendered html!

    Instead what you would do is a function that renders an url that triggers an action on an controller which returns the FileStreamResult.

    Another alternative is to embed the image if that is what you want.

    <img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
    

    Then you have to encode your image like in this post: Convert image path to base64 string but use your memory stream instead of reading from filepath.

    0 讨论(0)
提交回复
热议问题