首页 > 开发 > 综合 > 正文

Uploading Images to a Database - Part I (转)

2024-07-21 02:16:32
字体:
来源:转载
供稿:网友

uploading images to a database - part i
by dave, webmaster of www.123aspx.com  


intro
one of the popular questions of databases and the web is: "how can i upload an image into a database?" a few weeks ago there was a discussion thread going on at asplists.com about this topic. it turns out with asp.net, all of the controls and features are are already built into the framework to achieve this functionality. this article is not here to discuss the advantages or disadvantages of uploading binary data to a database, but merely how to do this.  so lets get started. if you want to skip the article, you can view all the code here.  
   
building our database table
we start out by building our database table. our image table is going to have a few columns describing the image data, plus the image itself.  here is the sql required to build our table in sql server.
create table [dbo].[image] (
[img_pk] [int] identity (1, 1) not null ,
[img_name] [varchar] (50) null ,
[img_data] [image] null ,
[img_contenttype] [varchar] (50) null
) on [primary] textimage_on [primary]
go

alter table [dbo].[image] with nocheck add
constraint [pk_image] primary key nonclustered
(
[img_pk]
) on [primary] go
i'm a great fan of having a single column primary key, and making that key an identity column, in our example, that column is img_pk. the next column is img_name,img_name is used to store a friendly name of our image, for example "mom and apple pie". img_data is actually our image data column, and is where we will be storing our binary image data.  img_contenttype will be used to record the content-type of the image, for example "image/gif" or "image/jpeg" so we will know what content-type we need to output back to the client, in our case the browser.
   
building our webform
now that we have a warm, fuzzy place to store our images, lets build a webform to upload our images into the database.
<form enctype="multipart/form-data" runat=server id=form1 name=form1>

    enter a friendly name
    <input type=text id=imgname runat="server" />
    
    <br>select file to upload:
<input id="uploadfile" type=file runat=server>
<asp:button text="upload me!" onclick="uploadbtn_click" runat=server/>
</form>
the first interesting point about our webform, is the attribute "enctype". enctype tells the browser and server that we will be uploading some type of binary data.  this binary data needs to be parsed, using a different mechanism from our normal text data.  the next control we of interest is the type=file control.  this control will present  the user with an upload file dialog box.  the user browses for the file they want to upload.  here is a picture of our form.
   
working with the uploaded image
once the user posts the data, we have to be able to  parse the binary data and send it to the database.  along with the main body of the code, we use 2 helper functions to achieve this.  the first function is used to connect to the database and the other function is used to insert the data into the database.  we connect to the database using a function we've posted on aspfree before. this function reads a connection string out of the database. you can find a better explanation of this function here .  i'll list it for completeness.  
    private function    sqlconnstring() as string
        rem -- get connstring from config.web
        dim context as httpcontext = httpcontext.current
        dim appsettings as hashtable = ctype(context.getconfig("appsettings"),hashtable)
        dim mydsn as string = ctype(appsettings("dsn"),string)

        return mydsn
     end function
   
inserting the image
we create another function to insert the image into the database.  this particular function was created using scott guthrie's adhoc database code builder. if you haven't seen it, i suggest you take a look at it, as it can save you a lot of time.  to use the code builder, you enter the basic sql syntax you want to use, in our case it was an insert statement (see following code).  and then you define the parameters of your query.  here is what our function ended up looking like:
function mydatabasemethod(imgname as string, imgbin as byte(), imgcontenttype as string) as integer
    dim connection as new sqlconnection( sqlconnstring )
    dim command as new sqlcommand( "insert into image (img_name,img_data,img_contenttype) values ( @img_name, @img_data,@img_contenttype )", connection )

    dim param0 as new sqlparameter( "@img_name", sqldatatype.varchar,50 )
    param0.value = imgname
    command.parameters.add( param0 )

    dim param1 as new sqlparameter( "@img_data", sqldatatype.image )
    param1.value = imgbin
    command.parameters.add( param1 )

    dim param2 as new sqlparameter( "@img_contenttype", sqldatatype.varchar,50 )
    param2.value = imgcontenttype
    command.parameters.add( param2 )

    connection.open()
    dim numrowsaffected as integer = command.executenonquery()
    connection.close()

   return numrowsaffected

end function
in this function we are passing in 3 different parameters
imgname - the friendly name we want to give out image data
imgbin -- the binary or byte array of our data
imgcontenttype - the content type of our image. for example: image/gif or image/jpeg

scott's database code builder does the rest of the work for us. the code builder creates our 3 parameters as sqlparameters and defines the type. our first sqlparameter is @img_name and is defined as a varchar with a length of 50.  the 2nd parameter, @img_data, is the binary or byte() of data and is defined with a data type of image. the last parameter is @img_contenttype, is defined as a varchar with a length of 50 characters.  the remainder of the function opens a connection to the database and executes the command by calling command.executenonquery().
   
calling our functions
ok, now that we have our worker functions written, let's go ahead and get our image data.  
            imgstream = uploadfile.postedfile.inputstream
            imglen = uploadfile.postedfile.contentlength
            imguploadedname = uploadfile.postedfile.filename
            dim imgbinarydata(imglen) as byte
            imgcontenttype = uploadfile.postedfile.contenttype
            imgname_value = imgname.value

            try
                if imgname_value.length < 1 then
                    imgname_value =     getlastrightof("/",imguploadedname )
                end if
            catch myex as exception
                    imgname_value =     getlastrightof("/",imguploadedname )
            end try

we need to access three important pieces of data for our example. we need the image:
name (imgname_value)
content-type (imgcontenttype)
and the image data. (imgbindarydata())
first we access to the image stream, which we are able to get by using the property uploadfile.postedfile.inputstream. (remember, uploadfile was the name of our upload control on the webform).    we also need to know how long the byte array we are going to create needs to be.  we can get this number by calling  uploadfile.postedfile.contentlength, and storing it's value in imglen.  once we have the length of the image, we create a byte array by dim imgbinarydata(imglen) as byte.  we access the content type of the image by accessing the contenttype property of uploadfile.postedfile. lastly we need the friendly name we are going to use for the image. in our code we actually capture two names. the original name of the file uploaded, and the friendly name entered by the user. if the user did not enter a friendly name we retrieve the original name of the image from uploadfile.postedfile.filename. however, uploadfile.postedfile.filename returns more than just the image name, it returns the entire uploaded image file path. an example might be: c:/temp/myimage.jpg. therefore, the image name we really want, is everything after the last "/". to do this, we write a little utility function:
     function getlastrightof(lookfor as string, mystring as string) as string
            dim strpos as integer
            strpos = mystring.lastindexof(lookfor)
            return mystring.substring(strpos + 1)
     end function
getlastrightof() finds the last positional instance of "/". once we have that position, stored in the variable strpos, we call an overloaded substring() method of the string object and return everything after the last "/". calling string.substring() looks like  substring(strpos + 1). we have to add 1 to strpos because the length of "/" needs to be accounted for.
   
the good stuff
ok, we know how to connect to the database, we know how to insert data into the database, and we have access to the uploaded image's properties.  but how do we pass the stream of the image to mydatabasemethod(). again, .net comes to the rescue. with 1 line of code we are able to access the image stream and convert it to a byte array.
     dim n as integer = imgstream.read(imgbinarydata, 0, imglen)
the stream object provides a method called read(). read() takes 3 parameters:
buffer - an array of bytes. a maximum of count bytes are read from the current stream and stored in buffer.
offset -the byte offset in buffer at which to begin storing the data read from the current stream.
count - the maximum number of bytes to be read from the current stream.
so we pass in our byte array, imgbinarydata; the place to start at, 0; and the amount of bytes we want to read.  n number of bytes read into our array is returned.
   
extending beyond images
because we are able to access the binary stream of data, images are not the only object we can store in the database.  some other objects might be streaming video, com objects, or sound clips.  as an example i also uploaded a streaming video into my database.  i ran a select query to show the results.
   
conclusion
so there we have it, asp.net provides us some easy functionality for uploading images into a database. in part ii, we will actually look at pulling these images out of a database and sending them to a browser.  the complete code used for this article can be found below.

image.sql
if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[image]') and objectproperty(id, n'isusertable') = 1)
drop table [dbo].[image]
go

create table [dbo].[image] (
[img_pk] [int] identity (1, 1) not null ,
[img_name] [varchar] (50) null ,
[img_data] [image] null ,
[img_contenttype] [varchar] (50) null
) on [primary] textimage_on [primary]
go

alter table [dbo].[image] with nocheck add
constraint [pk_image] primary key nonclustered
(
[img_pk]
) on [primary]
go

imgupload.aspx
<%@ page enablesessionstate="false" explicit="true" strict="true" maintainstate="false"%>
<%@import namespace="system.data.sql" %>
<%@import namespace="system.io"%>
<script language="vb" runat=server>

sub uploadbtn_click(sender as object, e as eventargs)
            dim imgstream as stream
            dim imglen as integer
            dim imgname_value as string
            dim imgcontenttype as string
            dim imguploadedname as string
            
            imgstream = uploadfile.postedfile.inputstream
            imglen = uploadfile.postedfile.contentlength
            imguploadedname = uploadfile.postedfile.filename
            dim imgbinarydata(imglen) as byte
            imgcontenttype = uploadfile.postedfile.contenttype
            imgname_value = imgname.value

            try
                if imgname_value.length < 1 then
                    imgname_value =     getlastrightof("/",imguploadedname )
                end if
            catch myex as exception
                    imgname_value =     getlastrightof("/",imguploadedname )
            end try

     dim n as integer = imgstream.read(imgbinarydata, 0, imglen)
     dim numrowsaffected as integer = mydatabasemethod(imgname_value, imgbinarydata, imgcontenttype)

    if numrowsaffected > 0 then
         response.write ( "<br> uploaded image " )
    else
         response.write ( "<br> an error occurred uploading the image.d " )
    end if
end sub

function getlastrightof(lookfor as string, mystring as string) as string
            dim strpos as integer
            strpos = mystring.lastindexof(lookfor)
            return mystring.substring(strpos + 1)
end function


function mydatabasemethod(imgname as string, imgbin as byte(), imgcontenttype as string) as integer
    dim connection as new sqlconnection( sqlconnstring() )
    dim command as new sqlcommand( "insert into image (img_name,img_data,img_contenttype) values ( @img_name, @img_data,@img_contenttype )", connection )

    dim param0 as new sqlparameter( "@img_name", sqldatatype.varchar,50 )
    param0.value = imgname
    command.parameters.add( param0 )

    dim param1 as new sqlparameter( "@img_data", sqldatatype.image )
    param1.value = imgbin
    command.parameters.add( param1 )

    dim param2 as new sqlparameter( "@img_contenttype", sqldatatype.varchar,50 )
    param2.value = imgcontenttype
    command.parameters.add( param2 )

    connection.open()
    dim numrowsaffected as integer = command.executenonquery()
    connection.close()

   return numrowsaffected

end function


private function sqlconnstring() as string
    rem -- get connstring from config.web
    dim context as httpcontext = httpcontext.current
    dim appsettings as hashtable = ctype(context.getconfig("appsettings"),hashtable)
    dim mydsn as string = ctype(appsettings("cntest"),string)

    return mydsn
end function

</script>
<html>
<title>upload images to a database </title>
<body>
<form enctype="multipart/form-data" runat=server id=form1 name=form1>

    enter a friendly name
    <input type=text id=imgname runat="server" />
    
    <br>select file to upload:
<input id="uploadfile" type=file runat=server>
<asp:button text="upload me!" onclick="uploadbtn_click" runat=server/>
</form>
</body>
</html>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表