数据库存取图片并在MVC3中显示在View中

根据路径读取图片:
byte[] img = System.IO.File.ReadAllBytes(@"d:\xxxx.jpg");

简介:在有些情况下需要将图片转换为二进制流存放在数据库中,当显示时再从数据库中读出来显示在界面上。

本文简单介绍数据库中图片的存取方法,并在MVC3中显示在Razor视图中。仅供初学者参考学习。

1. 将图片转换为二进制流

/// <summary>/// convert a picture file to byte array        /// </summary>        public byte[] GetBytesFromImage(string filename)        {            FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read);            int length = (int)fs.Length;            byte[] image = new byte[length];            fs.Read(image, 0, length);            fs.Close();            return image;        }

  

2. 将二进制文件写入数据库

/// <summary>///  write byte array to database/// </summary>public void StoreImageToDB(byte[] image){    string connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=123456";    string strSql = "INSERT INTO TestImage(image) Values(@image)";using (SqlConnection connection = new SqlConnection(connectionString))    {        SqlCommand cmd = new SqlCommand(strSql,connection);        cmd.Parameters.Add("@image", SqlDbType.Image).Value = image;        connection.Open();cmd.ExecuteNonQuery();        cmd.Clone();    }}

  

3. 从数据库中读取图片

/// <summary>/// get image from database/// </summary>public byte[] GetBytesFromDB(){    string connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=123456";    string strSql = "SELECT top 1 image FROM TestImage";using (SqlConnection connection = new SqlConnection(connectionString))    {        SqlCommand cmd = new SqlCommand(strSql,connection);        connection.Open();SqlDataReader reader = cmd.ExecuteReader();        byte[] temp = null;        if (reader.Read())        {            temp = (byte[])reader.GetValue(0);        }        return temp;    }}

4. 在Controller中添加返回图片的方法

/// <summary>/// Action that return the image file/// </summary>public FileResult Image(){   //get image from database   byte[] image = GetBytesFromDB();//return the image to View   return new FileContentResult(image, "image/jpeg");//or like below   //MemoryStream mem = new MemoryStream(image, 0, image.Length);   //return new FileStreamResult(mem, "image/jpg");

}

5. 在View中显示图片, 将src指定为我们返回图片的Action方法

<img alt="" src="/Home/Image" />

上面的方法都是我们自己实现且用SQL语句存取数据库,其实.NET框架已经给我们封装好了

很多现成的类,再加上 EF 存取数据库可以使我们的代码变得更加 elegant。

1. 前台上传图片

@using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" })) {<div>Upload new image: <input type="file" name="Image" /></div><input type="submit" value="Save" />}

它相当于 webform 中的 :

<form action="/Admin/Edit" enctype="multipart/form-data" method="post">

enctype = "multipart/form-data" 告诉浏览器将我们的文件流 post 到后台。

2. 将图片存入数据库

[HttpPost]public ActionResult Edit(Product product, HttpPostedFileBase image) {if (ModelState.IsValid) {if (image != null) {product.ImageMimeType = image.ContentType;product.ImageData = new byte[image.ContentLength];image.InputStream.Read(product.ImageData, 0, image.ContentLength);}// save the product
repository.SaveProduct(product);return RedirectToAction("Index");} else {// there is something wrong with the data valuesreturn View(product);}}

MVC框架会自动封装实例化我们的实体类和文件流并传到 post 方法中。

其中 HttpPostedFileBase 是一个抽象类,实际传过来的对象

是它的子类 HttpPostedFileWrapper 对象。

HttpPostedFileBase 类定义了很多操作文件流的属性和接口。

3. 在 view 中请求显示图片的 action

<img src="@Url.Action("GetImage", "Product", new { Model.ProductID })" />

其中读取图片流的方法如下:

public FileContentResult GetImage(int productId) {Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);if (prod != null) {return File(prod.ImageData, prod.ImageMimeType);} else {return null;}}

其中 FileContentResult  是 ActionResult 的子类 ,action 的返回类型有很多种,它们都继承自抽象类 ActionResult 。

转载于:https://www.cnblogs.com/weiweithe/p/4363458.html

MVC中根据后台绝对路径读取图片并显示在IMG中相关推荐

  1. img src请求后台值值能判断_MVC中根据后台绝对路径读取图片并显示在IMG中

    简介:在有些情况下需要将图片转换为二进制流存放在数据库中,当显示时再从数据库中读出来显示在界面上. 本文简单介绍数据库中图片的存取方法,并在MVC3中显示在Razor视图中.仅供初学者参考学习. 1. ...

  2. Unity读取图片并显示到UI中

    Unity读取图片并显示到UI中 方法一:将图片转换成字符串 代码 解释 效果图 方法二:将图片转换成字节数组 代码 解释 效果图 对比 在进行Unity开发时,经常会遇到将读取磁盘中图片显示到UI上 ...

  3. PyQt5(一) PyQt5安装及配置,从文件夹读取图片并显示,模拟生成素描图像

    目录 一.环境配置 1.1 安装PyQt5 1.2 安装Qt工具包 1.3 配置环境变量 ?1.4 测试PyQt5 ?1.5?配置PyCharm 二.QtDesigner 窗口简单介绍 2.1 初始界 ...

  4. C++ opencv 4.5 imread() 读取图片,显示为空的解决办法

    C++ opencv 4.5 imread() 读取图片,显示为空的解决办法 一.路径问题 先查看下路径问题,如果使用的是相对路径,先查看下当前路径,判断输入的路径是否有错: #include < ...

  5. 图片保存到数据库和从数据库读取图片并显示(C#)

    图片保存到数据库的方法: public void imgToDB(string sql) {   //参数sql中要求保存的imge变量名称为@images //调用方法如:imgToDB(" ...

  6. 在VC中实现模拟键盘,输入内容并显示在ListBox中。

    网上找的,还没试过,希望对楼主有帮助 模拟键盘按键 自动输入文字 键盘对于每个操作电脑的人员来说是最熟悉不过的了.键盘上的按键可分为两类: 按下后会在电脑的输入窗口上出现对应字符的按键,如字母键和数字 ...

  7. python:【一文学会】批量读取图片、替换背景图中的像素位置、批量添加文本

    **导语:**有时候为了提升效率节省时间,我们需要对文件夹中的图片进行批量处理.由于工作和学习所需,新接触Python,并且实现批量图片操作. 本文处理效果: 以及这样: 正文开始 步骤:实现一张背景 ...

  8. 在jsp中通过I/O流方式读取图片并展示到页面

    之前在做一个项目时用到了图片上传并立即展示到页面浏览,而且图片存放在硬盘上的一个文件夹中而非在工程与数据库中,这就会出现一个问题,如果不是在开发程序环境中访问图片页面,则会出现图片不能展示情况,原因很 ...

  9. java中相对路径怎么写_java中如何使用相对路径读取文件

    java中使用相对路径读取文件的方法:1.使用文件[File file = new File("src/test.txt")]方法:2.使用类的相对路径:3.使用当前线程的类加载器 ...

最新文章

  1. react 日期怎么格式化_手写React的Fiber架构,深入理解其原理
  2. MathType的公式Latex到Katex转换程序
  3. Python 神工具包!翻译、文字识别、语音转文字统统搞定
  4. php 回车键触发事件,回车触发事件 - 范思哲思考者的个人空间 - OSCHINA - 中文开源技术交流社区...
  5. POJ 1269 Intersecting Lines(求直线交点)
  6. 5G牌照提前发放 将对整个产业界带来哪些影响?
  7. Python用20行代码实现一个验证码的输入与验证(完整源码)
  8. 相机参数设置程序_摄影:相机通用的参数设置,10个方面带你学会使用相机拍照...
  9. Zynq7000硬件开发之电源供电系统(PDN)设计(一)
  10. Android 适配深色模式
  11. 保险行业线上引流渠道有哪些?还在为没有客户而烦恼吗?这几招教你线上低成本引流获客!
  12. 51nod 1428 贪心
  13. Python怼人代码,让编程变得更有趣
  14. [项目]用C++实现的壳(扩展版)
  15. 六十甲子日吉凶时辰对照表
  16. MySQL 表分区?涨知识了
  17. java8函数式编程笔记-科里化
  18. 就决定是你啦!苏菲婆5! —— 谈谈我对Surface Pro 5的使用体验以及各种骚操作
  19. 数学建模学习(60):matlab回归分析及残差图绘制
  20. 抢下硅谷自动驾驶出租车运行首秀的,竟是家中国公司?

热门文章

  1. 数据结构之二叉树的一些基本操作
  2. 如何保证MongoDB的安全性? 1
  3. Win10安全特性之执行流保护
  4. Linux+php+memcache+APC加速PHP网站
  5. 插入排序:表折半插入
  6. javax.servlet.jsp.JspTagException:
  7. 经验:Windows To Go准备工作
  8. Spring事务那些事儿
  9. 模拟传输和数字传输的优缺点
  10. mysql concat例子_MYSQL中CONCAT详解