将图片插入数据库并使用asp.net读取出来的正确方
2024-07-10 12:55:18
供稿:网友
书写本文是因为今天见到csdn的首页上一篇存在明显失误的名为“在asp.net中从sqlserver检索(retrieve)图片”的文章。不说其错误是因为用其方法确实能从数据库中读取出图片并显示在浏览器,说其失误是因为代码的意图不能被完全的实现,作者也似乎对http协议以及浏览器在处理http数据的流程一知半解。
1、如何出错
以下是这片文章提到的方法:
public sub page_load(sender as object, e as eventargs)
dim myconnection as new sqlconnection(configurationsettings.appsettings("connectionstring"))
dim mycommand as new sqlcommand("select * from person", myconnection)
try
myconnection.open()
dim mydatareader as sqldatareader
mydatareader = mycommand.executereader(commandbehavior.closeconnection)
do while (mydatareader.read())
response.contenttype = mydatareader.item("personimagetype")
response.binarywrite(mydatareader.item("personimage"))
loop
myconnection.close()
response.write("person info successfully retrieved!")
catch sqlexc as sqlexception
response.write("read failed : " & sqlexc.tostring())
end try
end sub
显然,编程者是想将person表中所有的记录中的personimage字段所存储的图片一次性地输出到浏览器中,并且在输出成功地情况下在已输出的图片的下方打印出“person info successfully retrieved!”信息。然而事实上上述代码仅仅能正确地输出第一条记录中的图片。对于浏览器来说,一个http请求获取一个文件(html或者图片),所以以上代码的输出将被作为一个文件(类型依据response.contenttype = mydatareader.item("personimagetype")定)被浏览器处理。如果http相应的类型是image/jpeg之类的图片,则浏览器使用相应的图片解析功能对这一个图片文件进行解析。因此,上述代码的显示结果只能是第一条记录personimage字段的图片。后面的记录输出的图片数据将成为第一张图片的多余数据(此点具有普遍性,但并非绝对,依图片的格式而定),从而后面的“person info successfully retrieved!”的信息也自然无法本显示出来,因为这些信息已经是图片文件里面的编码了。
2、正确的做法
a、将图片输入到数据库中,以下是一个将图片输入到数据库的代码片断:(完整的demo程序见附录一)
filestream fs=file.openread(filepath.text);
byte[] content=new byte[fs.length];
fs.read(content, 0,content.length);
fs.close();
sqlconnection conn=new sqlconnection("integrated security=sspi;persist security info=false;initial catalog=databaseimage;data source=(local)");
conn.open();
sqlcommand comm=conn.createcommand();
comm.commandtext="insert into images(image, contenttype) values(@image, @contenttype)";
comm.commandtype=commandtype.text;
comm.parameters.add("@image", sqldbtype.image).value=content;
comm.parameters.add("@contenttype", sqldbtype.nvarchar).value=
getcontenttype(new fileinfo(filepath.text).extension.remove(0,1));
if(comm.executenonquery()==1)
{
messagebox.show("successfully insert image into database!");
}
else
{
messagebox.show("failed to insert image into database");
}
conn.close();
b、将数据库中的图片读出来的代码片断:(完整demo程序见附录二)
try{
sqlconnection conn=new sqlconnection("integrated security=sspi;persist security info=false;initial catalog=databaseimage;data source=(local)");
conn.open();
sqlcommand comm=conn.createcommand();
comm.commandtext="select * from images where [email protected]";
comm.commandtype=commandtype.text;
comm.parameters.add("@id", sqldbtype.bigint).value=int.parse(request["id"]);
sqldatareader reader=comm.executereader();
while(reader.read())
{
response.contenttype=reader["contenttype"].tostring();
response.binarywrite((byte[])reader["image"]);
}
response.end();
conn.close();
}
catch
{
response.end();
}
这段代码可置于page_load事件中,数据图片要注意的两点是:
一、 设置正确的contenttype(http中的content-type),图片的content-type格式一般为image/*,如jpeg为image/jpeg,bmp为image/bmp等等。
二、 仅仅输出一张图片二进制流,asp.net 中page_load事件先于页面输出被触发,因此图片的输出可以在此事件中进行,直接操作reponse对象,避免输出与图片无关的而外信息(额外的第二张图片或者文字)。图片的二进制流输出后及时使用response.end()方法结束http响应,避免页面中的额外信息被asp.net的引擎默认输出到客户端。
希望此文能够起到抛砖引玉的作用!^_^
附录一:
mainform.cs
using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.io;
using system.windows.forms;
namespace insertimagetodatabase
{
public class mainform : system.windows.forms.form
{
private system.windows.forms.openfiledialog openfiledlg;
private system.windows.forms.textbox filepath;
private system.windows.forms.button browsebutton;
private system.windows.forms.button insertbutton;
/// <summary>
/// required designer variable.
/// </summary>
private system.componentmodel.container components = null;
public mainform()
{
//
// required for windows form designer support
//
initializecomponent();
//
// todo: add any constructor code after initializecomponent call
//
}
/// <summary>
/// clean up any resources being used.
/// </summary>
protected override void dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
#region windows form designer generated code
/// <summary>
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
{
this.openfiledlg = new system.windows.forms.openfiledialog();
this.filepath = new system.windows.forms.textbox();
this.browsebutton = new system.windows.forms.button();
this.insertbutton = new system.windows.forms.button();
this.suspendlayout();
//
// openfiledlg
//
this.openfiledlg.defaultext = "*.jpg;*.gif;*.bmp;*.png";
this.openfiledlg.filter = "image files|*.jpg;*.gif;*.bmp;*.png|all files|*.*";
//
// filepath
//
this.filepath.location = new system.drawing.point(16, 16);
this.filepath.name = "filepath";
this.filepath.readonly = true;
this.filepath.size = new system.drawing.size(168, 20);
this.filepath.tabindex = 0;
this.filepath.text = "";
//
// browsebutton
//
this.browsebutton.location = new system.drawing.point(200, 16);
this.browsebutton.name = "browsebutton";
this.browsebutton.tabindex = 1;
this.browsebutton.text = "&browse";
this.browsebutton.click += new system.eventhandler(this.browsebutton_click);
//
// insertbutton
//
this.insertbutton.enabled = false;
this.insertbutton.location = new system.drawing.point(200, 56);
this.insertbutton.name = "insertbutton";
this.insertbutton.tabindex = 2;
this.insertbutton.text = "&insert";
this.insertbutton.click += new system.eventhandler(this.insertbutton_click);
//
// mainform
//
this.autoscalebasesize = new system.drawing.size(5, 13);
this.clientsize = new system.drawing.size(292, 273);
this.controls.add(this.insertbutton);
this.controls.add(this.browsebutton);
this.controls.add(this.filepath);
this.formborderstyle = system.windows.forms.formborderstyle.fixedsingle;
this.maximizebox = false;
this.name = "mainform";
this.text = "insert image to database";
this.resumelayout(false);
}
#endregion
/// <summary>
/// the main entry point for the application.
/// </summary>
[stathread]
static void main()
{
application.run(new mainform());
}
private void browsebutton_click(object sender, system.eventargs e)
{
if(openfiledlg.showdialog()==dialogresult.ok)
{
filepath.text=openfiledlg.filename;
insertbutton.enabled=true;
}
}
private void insertbutton_click(object sender, system.eventargs e)
{
filestream fs=file.openread(filepath.text);
byte[] content=new byte[fs.length];
fs.read(content, 0,content.length);
fs.close();
sqlconnection conn=new sqlconnection("integrated security=sspi;persist security info=false;initial catalog=databaseimage;data source=(local)");
conn.open();
sqlcommand comm=conn.createcommand();
comm.commandtext="insert into images(image, contenttype) values(@image, @contenttype)";
comm.commandtype=commandtype.text;
sqlparameter param=comm.parameters.add("@image", sqldbtype.image);
param.value=content;
comm.parameters.add("@contenttype", sqldbtype.nvarchar).value=
getcontenttype(new fileinfo(filepath.text).extension.remove(0,1));
if(comm.executenonquery()==1)
{
messagebox.show("successfully insert image into database!");
}
else
{
messagebox.show("failed to insert image into database");
}
conn.close();
}
private string getcontenttype(string extension)
{
string type="jpeg";
if(extension=="jpg")
{
type="jpeg";
}else
{
type=extension;
}
return "image/"+type;
}
}
}
附录二:
readimage.aspx
<%@ page language="c#" codebehind="readimage.aspx.cs" autoeventwireup="false" inherits="readimage.readimage"%>
readimage.aspx.cs
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
namespace readimage
{
/// <summary>
/// summary description for readimage.
/// </summary>
public class readimage : system.web.ui.page
{
private void page_load(object sender, system.eventargs e)
{
try{
sqlconnection conn=new sqlconnection("integrated security=sspi;persist security info=false;initial catalog=databaseimage;data source=(local)");
conn.open();
sqlcommand comm=conn.createcommand();
comm.commandtext="select * from images where id>@id";
comm.commandtype=commandtype.text;
comm.parameters.add("@id", sqldbtype.bigint).value=int.parse(request["id"]);
sqldatareader reader=comm.executereader();
while(reader.read())
{
response.contenttype=reader["contenttype"].tostring();
response.binarywrite((byte[])reader["image"]);
}
response.write("aaaaaa");
response.end();
conn.close();
}
catch
{
response.end();
}
}
#region web form designer generated code
override protected void oninit(eventargs e)
{
//
// codegen: this call is required by the asp.net web form designer.
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
{
this.load += new system.eventhandler(this.page_load);
}
#endregion
}
}