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

How to upload an image on one server and save it on another using ASP.NET and web services

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
7 Feb 2013CPOL2 min read 32K   13   3
Upload an image on one server and save it on another.

Introduction

There can be a need to upload images or text files on one server and save them on another. This article will help you achieve such a task using ASP.NET and web services.

Using the code

There would be two separate projects to cover this query. One project for a website and another for a web service using VS 2008 or VS 2010. I am assuming you would have created both projects.

There is a simple logic in achieving this target. We will browse the file from one server and save it on the destination using a web service hosted on the destination server.

Website Project

  1. Place the control on an ASPX page - you need a Browse button, Save button, and a textbox to show the notifications or errors. 
  2. Under the Save button click event, place the below code. Please note: you need to add a reference of the web service you will make in another project. I have explained below the details about the web service.
  3. The browsed file InputStream is converted into XML using byte[] using serialization.
  4. The myData byte[] object is serialized ser.Serialize(wr, myData); using a string builder and string writer. The string is loaded into XML.
  5. This XML is passed as one of the parameters under the web service hosted on another project. You can pass as many parameters as needed based on your requirements.
C#
protected void btnSaveImage_Click(object sender, EventArgs e)
{
    string UploadFileFolderPath = "C:\\Intel";
    System.IO.Stream MyStream;

    if (btnBrowse.PostedFile != null)
    {
        HttpPostedFile myFile = btnBrowse.PostedFile;

        int fileLength = myFile.ContentLength;

        byte[] myData = new byte[fileLength];
        myFile.InputStream.Read(myData, 0, fileLength);
        // Gor in Binary Data
        XmlSerializer ser = new XmlSerializer(myData.GetType());

      

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter wr = new System.IO.StringWriter(sb);
        ser.Serialize(wr, myData);
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());
        localhost.ImageWebService ws = new localhost.ImageWebService();
        ws.SaveImage(sb.ToString(), myFile.FileName.ToString(), fileLength);
    }
    else
    {
        txtPath.Text = "error: please check the path";
    }

}

Webservice project code

C#
[WebMethod()]
public string SaveImage(string imageStreamPath, string imageName, int fileLength)
{
    string result = "";
    string UploadFileFolderPath = "C:\\Ankit";

    byte[] dsXML = new byte[fileLength];

    System.IO.StringReader read = new StringReader(imageStreamPath);

    System.Xml.XmlReader reader = new XmlTextReader(read);
    XmlSerializer ser = new XmlSerializer(dsXML.GetType());
    object obj = ser.Deserialize(reader);
    dsXML = (byte[])obj;

    ByteArrayToFile(imageName, dsXML);

    return result;
}

public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
    try
    {
        // Open file for reading
        _FileName = "C:\\Users\\ankitjain.AVALONSOLUTIONS\\Documents\\" + 
          "visual studio 2010\\Projects\\WebServices\\WebServices\\"  + _FileName;


        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, 
                 System.IO.FileMode.Create, System.IO.FileAccess.Write);

        // Writes a block of bytes to this stream using data from a byte array.
        _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

        // close file stream
        _FileStream.Close();

        return true; 
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    // error occured, return false
    return false;
} 

Webservice Project

Paste the above code under your ASMX page.

  1. Create a method SaveImage(string imageStreamPath, string imageName, int fileLength).
  2. The imageStreamPath contains the Browse File InputStream as an XML. I have deserialized it. Please note: you need the fileLength parameter.
  3. Here we need an XML reader and string reader instead of an XML load and string writer.
  4. The ByteArrayToFile method converts the deserialized file path stream and saves it to the destination folder.

Please note: both projects will go parallel. You need to add a reference of the web service to your website project.

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionReg/- uplode image Pin
Member 1141381028-Mar-15 21:08
Member 1141381028-Mar-15 21:08 
GeneralXML for binary data? Pin
John Brett4-Feb-13 2:00
John Brett4-Feb-13 2:00 
GeneralEditing Pin
DaveAuld4-Feb-13 0:06
professionalDaveAuld4-Feb-13 0:06 

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.