Developing An Image Upload Web Service

发布时间: 2007-01-24 11:34    作者: 未知    来源: 未知    浏览:    评论


Developing An Image Upload Web Service


By: Bipin Joshi
Level: Intermediate
Posted Date: 5/31/2002
Tested with ASP.NET v1.0 (RTM)
Click for Printable Version
Click here to download sample code


Member Rating: 3.90 (Rated by 10 members)
Rate This Item


ASP.NET Web Services provide 'Web callable' functions based on industry standards like HTTP, XML and SOAP. Since Web Services heavily rely on XML, all the data that is passed to and returned from a Web Service must be plain text. However, in certain applications we do need to pass binary data. Say for example I want to pass images from my Web form to a Web Service to save in some central repository and then retrieve them back. Does this mean that Web Services cannot be used for such data transfer? Certainly not. In fact ASP.NET Web Services make it easy to pass such data by hiding the encoding and decoding involved. Typically when you want to pass binary data you will declare the parameter of the Web method or return value of the Web method as a byte array. ASP.NET Web Services will automatically encode/decode this data using Base64 encoding. (Base64 encoding is the same encoding that is used for email MIME attachments.) In this example we develop an image upload Web Service that stores and retrieves images from SQL Server database.
SQL Server Database Table
To work with example you need a table in SQL server database called IMAGES. The following script can be used to create this table.

CREATE TABLE [dbo].[IMAGES] (
  [id] [int] IDENTITY (1, 1) NOT NULL ,
  [imgdata] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

The table contains two columns - ID that represents the primary key and IMGDATA that stores binary image data. Note that I have created this table in Northwind database itself; you may want to create it in some other database.
Creating the Web Service
Now, let us proceed with creating the Web Service. Create a new Web Service project in VS.NET and add the following two Web methods to it.

<WebMethod()> Public Function SaveImage(ByVal imgdata() As Byte) As String
  Dim connstr As String = "Integrated Security=SSPI;User ID=sa;Initial Catalog=Northwind;Data Source=SERVER\netsdk"
    Dim cnn As New SqlConnection(connstr)
    cnn.Open()
    Dim cmd As New SqlCommand("insert into images values(@img)", cnn)
    cmd.Parameters.Add(New SqlParameter("@img", imgdata))
    cmd.ExecuteNonQuery()
  End Function
  <WebMethod()> Public Function RetrieveImage(ByVal imgid As Integer) As Byte()
    Dim connstr As String = "Integrated Security=SSPI;User ID=sa;Initial Catalog=Northwind;Data Source=SERVER\netsdk"
    Dim cnn As New SqlConnection(connstr)
    Dim cmd As New SqlCommand("select * from images where id=" & imgid, cnn)
    cnn.Open()
    Dim dr As SqlDataReader = cmd.ExecuteReader
    dr.Read()
    Dim bindata() As Byte = dr.GetValue(1)
    Return bindata
  End Function

The method SaveImage accepts a byte array containing image data and saves it to the images table. The second method accepts image id to be retrieved and returns a byte array from the Web method.
Next, we will develop a Web client that presents UI for uploading files and calls this Web Service internally.
Creating the Client for the Web Service
Create a new Web application in VS.NET and add a Web reference to the Web Service we developed in the previous sections. Now, add a new WebForm called WebForm1 to the project. Put a File HTML server control and Button Web control on the form. The form should look like this:




The following is the markup of the WebForm:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="BinaryDataWC.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
      <INPUT style="Z-INDEX: 101; LEFT: 164px; POSITION: absolute; TOP: 51px" type="file" id="File1" name="File1" runat="server">
      <asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 22px; POSITION: absolute; TOP: 48px" runat="server">Select File to Upload :</asp:Label>
      <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 180px; POSITION: absolute; TOP: 94px" runat="server" Text="Upload"></asp:Button>
    </form>
  </body>
</HTML>

Note that the form has EncType attribute set to multipart/form-data. This is necessary in order to upload files.
Now, write the following code in the click event of the Upload button:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Dim ws As New localhost.Service1()
  Dim s As Stream = File1.PostedFile.InputStream
  Dim data(File1.PostedFile.ContentLength - 1) As Byte
  s.Read(data, 0, File1.PostedFile.ContentLength)
  ws.SaveImage(data)
End Sub

Here, we have created instance of Web Service class (actually proxy class). We fetched the file content into a byte array and then pass this array to the SaveImage Web method.
It's time now to develop another WebForm that will retrieve images from the database.

Add a new WebForm to the project called WebForm2 and put a label, TextBox, button and image Web control on it. The TextBox is used to specify the image id to be retrieved. We will retrieve the image as a byte array, save it in some file and then bind the image Web control to the file. The following is the markup of the WebForm:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm2.aspx.vb" Inherits="BinaryDataWC.WebForm2"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <title>WebForm2</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
      <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 271px; POSITION: absolute; TOP: 29px" runat="server" Text="Retrieve"></asp:Button>
      <asp:Label id="Label1" style="Z-INDEX: 104; LEFT: 31px; POSITION: absolute; TOP: 31px" runat="server">Image ID :</asp:Label>
      <asp:TextBox id="TextBox1" style="Z-INDEX: 103; LEFT: 108px; POSITION: absolute; TOP: 30px" runat="server"></asp:TextBox>
      <asp:Image id="Image1" style="Z-INDEX: 101; LEFT: 28px; POSITION: absolute; TOP: 70px" runat="server"></asp:Image>
    </form>
  </body>
</HTML>

Write the following code in the click event of Retrieve button:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  Dim ws As New localhost.Service1()
  Dim data() As Byte = ws.RetrieveImage(TextBox1.Text)
  Dim s As New FileStream(Server.MapPath(Request.ApplicationPath) & "\sample.jpg", FileMode.Create)
  s.Write(data, 0, data.Length)
  s.Close()
  Image1.ImageUrl = Server.MapPath(Request.ApplicationPath) & "\sample.jpg"
End Sub

Here, we have created a disk file to hold the retrieved bytes. The following screen shows a sample run of the WebForm.


Summary
In this article we saw how to develop an image upload Web Service. Web Services are based on standards like XML and SOAP that are 'Text Only'. However, ASP.NET Web Services make it easy to pass binary data to and from the Web Service by automatically encoding the data using Base64 encoding.

 
Smile Big Smile Surprise Stick out tongue Wink Sad Tongue Tied Indifferent Crying Embarrassed Cool Angry Angel Devil [8-|] [:#] [:-*] [:^)] [<:o)] [|-)] Yes Beer Left Hug Music Star Time Snail Pizza Automobile Umbrella Computer Storm [mo] [8o|] [^o)] [+o(] [*-)] [8-)] Coffee No Drinks [Z] Right Hug Cake Broken Heart Gift Wilted Flower Movie Dog Idea Sleep Email Travel Paradise
呢称:

加粗 斜体 下划线 链接 图片 代码 邮件地址 引用 列表

最多只能输入100个字符

Tags

SQL 数据库 asp.net C# XML 控件 .NET教程 程序 事件 数据 安全 代码 Server 客户端 验证 数据库专栏 接口 文件 Oracle DataSet 函数 DataGrid 问题 .net return C#语言 JavaScript 服务 IIS 对象 语句 windows 继承 时间 web.config 设计 开发 参数 变量 解决 字符 ADO.net 环境 VB.Net语言 web 异常 工具 服务器 计算 实例 OLEDB Application VB Word WebService insert asp net 安装 记录

精华推荐

更多

精品下载

更多