Developing An Image Upload Web Service

80酷酷网    80kuku.com

  web
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 101; LEFT: 164px; POSITION: absolute; TOP: 51px" type="file" id="File1" name="File1" runat="server">
      <asp:Label id="Label1" 103; LEFT: 22px; POSITION: absolute; TOP: 48px" runat="server">Select File to Upload :</asp:Label>
      <asp:Button id="Button1" 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" 102; LEFT: 271px; POSITION: absolute; TOP: 29px" runat="server" Text="Retrieve"></asp:Button>
      <asp:Label id="Label1" 104; LEFT: 31px; POSITION: absolute; TOP: 31px" runat="server">Image ID :</asp:Label>
      <asp:TextBox id="TextBox1" 103; LEFT: 108px; POSITION: absolute; TOP: 30px" runat="server"></asp:TextBox>
      <asp:Image id="Image1" 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.
 

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: