数据库存图片和文件,客户端浏览图片或下载文件

来源:互联网 发布:oppou529软件 编辑:程序博客网 时间:2024/06/09 16:04

数据库存图片和文件,客户端浏览图片或下载文件(通过Model层,多层应用) 

1、数据库:

 

  

2、模型层:

 

 

3、DAL层:

 

4、BLL业务逻辑层(省略)

 

5、界面层

(1)、添加:

 

(2)、BLOB输出页面:(图片显示或文件下载)

去除aspx文件中的所有HTML代码,只留一行声明行

 

 

(3)、展示页:

 

(4)、列表页

 

 

 

 

 6、小结:

(1)、从上传控件到byte数组:

int len = upload_file.ContentLength;                         //读上传文件,上传文件字节大小
bo.AttachmentFile = new byte[len];                           //读上传文件,初始化一个byte数组,长度为上传文件字节大小
upload_file.InputStream.Read(bo.AttachmentFile, 0, len);     //读上传文件,上传文件.输入流.读(字节数组,从0开始,长度为文件大小)

(2)、从byte数组插入到数据库Image类型的字段里:

SqlParameter para_AttachmentFile = new SqlParameter("@AttachmentFile", SqlDbType.Image); //参数类型为Image
para_AttachmentFile.Value = bo.AttachmentFile;
paras.Add(para_AttachmentFile);

(3)、从数据库Image类型的字段读出到byte数组:
bo.AttachmentFile = (byte[])objReader.GetValue(2);

(4)、从byte数组输出到aspx页面:

    (4.1)提供下载:

private void ExportDownload(bol.Article bo)
{
    string fileName = string.Format("attch_{0}.{1}", bo.Pkid, bo.FileExtName); //客户端保存的文件名

    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "utf-8";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Response.ContentType = "application/octet-stream";
    Page.EnableViewState = false;
    Response.BinaryWrite(bo.AttachmentFile);
}

    (4.2)图片输出显示:

private void ExportImage(bol.Article bo)
{
    MemoryStream stream = new MemoryStream();
    stream.Write(bo.AttachmentFile, 0, bo.AttachmentFile.Length);
    Bitmap bitmap = new Bitmap(stream);

    string content_type = "image/jpeg";          //默认为jpg格式
    ImageFormat img_format = ImageFormat.Jpeg;   //默认为jpg格式
    if (bo.FileExtName.ToLower().CompareTo("gif") == 0)
    {
        content_type = "image/gif";
        img_format = ImageFormat.Gif;
    }
    else if ("jpg|jpeg|jpe".Contains(bo.FileExtName.ToLower()))
    {
        content_type = "image/jpeg";
        img_format = ImageFormat.Jpeg;
    }

    Response.ContentType = content_type;
    bitmap.Save(Response.OutputStream, img_format);
}

 

原创粉丝点击