Click here to Skip to main content
13,147,383 members (27,568 online)
Click here to Skip to main content
Add your own
alternative version


6 bookmarked
Posted 29 Mar 2013

Submit Images to Web Service and Get Them Back

, 29 Mar 2013
Rate this:
Please Sign up or sign in to vote.
Submit images to a web service and get them back.


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.


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.


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".

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 
        // 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 
        // clean up 
        // 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.

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...
        //file found, return it 
        context.Response.ContentType = "image/jpeg"; 

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.

[WebMethod, Description("Get image content")] 
public byte[] GetImageFile(string fileName) 
    if (System.IO.File.Exists
    	("~/TransientStorage/") + fileName)) 
        return System.IO.File.ReadAllBytes(
          	("~/TransientStorage/") + fileName); 
        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"> 
                    <asp:Image id="myImage" 
                    runat="server"  Width="140px" Height="140px"
                    ImageUrl='<%# string.Format
                    ("~/Handler1.ashx?fileName={0}",Eval("imageFile"))%>' />

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.

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);
    DataList1.DataSource = ds; 

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.


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


About the Author

Omar Isaid
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.

You may also be interested in...


Comments and Discussions

Questionwhere do you save images in the database? Pin
Milan Andreeev5-Mar-14 3:14
memberMilan 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 30 Mar 2013
Article Copyright 2013 by Omar Isaid
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid