Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Tip/Trick

Submit Images to Web Service and Get Them Back

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
29 Mar 2013CPOL2 min read 55.7K   1.9K   6   1
Submit images to a web service and get them back.

Introduction

This tip shows how to upload images through a web service and get images back from the web service using a generic handler and display them on the DataList ASP.NET control.

Background

I asked these questions in many forums including CodeProject and found useful answers and wanted to show this idea as a small proof of concept.

Using the Code

WebForm1.aspx is responsible for uploading images using the FileUpload control and send image as an array of bytes and file name parameters to the web method public string UploadFile(byte[] f, string fileName) to be saved at a directory in the XML web service.

WebForm1.aspx.cs

C#
protected void Button1_Click(object sender, EventArgs e) 
{ 
    // Upload the image and send it to the XML web service  
    // you can set limitations on the file type and file size  
    // according to your specification 
    byte[] file = FileUpload1.FileBytes; 
    MyService.Service1 serv = new MyService.Service1(); 
    serv.UploadFile(file, FileUpload1.FileName); 
}

The web method UploadFile of the XML web service gets the images as an array of bytes and writes it to the directory TransientStorage as a stream of bytes, and you need to be sure to edit the permissions of the directory TransientStorage to avoid the exception "Unauthorized access".

C#
[WebMethod] 
public string UploadFile(byte[] f, string fileName) 
{ 
    // the byte array argument contains the content of the file 
    // the string argument contains the name and extension 
    // of the file passed in the byte array 
    try 
    { 
        // instance a memory stream and pass the 
        // byte array to its constructor 
        MemoryStream ms = new MemoryStream(f); 
        // instance a filestream pointing to the 
        // storage folder, use the original file name 
        // to name the resulting file 
        FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath
                    ("~/TransientStorage/") + fileName, FileMode.Create);

        // write the memory stream containing the original 
        // file as a byte array to the filestream 
        ms.WriteTo(fs); 
        // clean up 
        ms.Close(); 
        fs.Close(); 
        fs.Dispose(); 
        // return OK if we made it this far 
        return "OK"; 
    } 
    catch (Exception ex) 
    { 
        // return the error message if the operation fails 
        return ex.Message.ToString(); 
    } 
}

Now how do we get the image from the web service?

The generic handler calls the web method public byte[] GetImageFile(string fileName) that exists at the XML web service to get the image as a stream of bytes using the image name and the names of the images saved in this example in the database.

C#
public void ProcessRequest(HttpContext context) 
{ 
    MyService.Service1 ws = new MyService.Service1(); 
    //instantiate your webservice  
    //invoke GetImage method passing file name as param 
    string fileName = context.Request["fileName"]; 
    byte[] binImage = ws.GetImageFile(fileName); 
    if (binImage.Length == 1)
    { 
        //File Not found by the web services
        //Maybe you want to display an alternate image here...
    } 
    else
    {
        //file found, return it 
        context.Response.ContentType = "image/jpeg"; 
        context.Response.BinaryWrite(binImage); 
    } 
}

The XML web service will read the image using the file name and get the image back as an array of bytes to the generic handler.

C#
[WebMethod, Description("Get image content")] 
public byte[] GetImageFile(string fileName) 
{ 
    if (System.IO.File.Exists
    (System.Web.Hosting.HostingEnvironment.MapPath
    	("~/TransientStorage/") + fileName)) 
    { 
        return System.IO.File.ReadAllBytes(
          System.Web.Hosting.HostingEnvironment.MapPath
          	("~/TransientStorage/") + fileName); 
    } 
    else 
    { 
        return new byte[] { 0 }; 
    } 
}

WebForm2 displays the images at the DataList, ImageUrl attribute of the image inside ItemTemplate will be mapped to the generic handler result

<asp:DataList ID="DataList1" runat="server"  
        onitemcommand="DataList1_ItemCommand" RepeatColumns="4"> 
    <ItemTemplate> 
        <table> 
            <tr> 
                <td> 
                    <asp:Image id="myImage" 
                    runat="server"  Width="140px" Height="140px"
                    ImageUrl='<%# string.Format
                    ("~/Handler1.ashx?fileName={0}",Eval("imageFile"))%>' />
                </td>  
            </tr> 
        </table> 
    </ItemTemplate> 
</asp:DataList>

The page load will bind the DataList to the DataTable, which contains the field 'imgFile' that represents the names of the images stored at the XML web service directory.

C#
protected void Page_Load(object sender, EventArgs e)
{ 
    string conStr = @"Data Source=OMAR-PC;Initial Catalog=TestDB;User ID=sa;Password=123@asu;";
    SqlConnection con = new SqlConnection(conStr);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "SELECT * FROM Table1";
    cmd.Connection = con; 
    DataSet ds = new DataSet(); 
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    adapter.Fill(ds); 
    DataList1.DataSource = ds; 
    DataList1.DataBind();  
}

The table 'Table1' will have the field 'imageFile' that contains the names of the images that will be displayed at the DataList control.

Points of Interest

For the first time, I learned how to use a generic handler in an example.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
Jordan Jordan
Omar Adnan Isaid Junior developer interested to learn more about web development and meet experts in this field aims to add something unique to IT field.
http://omarpost.blogspot.com/

Comments and Discussions

 
Questionwhere do you save images in the database? Pin
Milan Andreeev5-Mar-14 3:14
Milan Andreeev5-Mar-14 3:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.