Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Silverlight » Upload multiple files using Generic Handler in Silverlight 4

Upload multiple files using Generic Handler in Silverlight 4

In this article we will learn how to upload multiple files using Generic Handler in Silverlight 4.

Author Rank :
Page Views : 7064
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


This article describes for you the basic use of generic handler and how to upload multiple files using generic handler in Silverlight.

What is Generic Handler? Generic handlers have an extension of ASHX. They're equivalent to custom handlers written in C Sharp or Visual Basic.NET in that they contain classes that fully implement IHttpHandler. They're convenient in the same way ASPX files are convenient. You simply surf to them and they're compiled automatically.

First of all make a new Silverlight project.

Image1.jpg
 

Image 1.

Now right click on web project and click "Add New Item" and add a Generic Handler"
 
Image2.jpg

Image 2.

By default Generic Handler has this code.

public class Handler2 : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Change ProcessRequest method.

public void ProcessRequest(HttpContext context)
{
    var imageName = context.Request["file"];
    string str;
    using (StreamReader streamReader = new StreamReader(context.Request.InputStream))
    {
        str = streamReader.ReadToEnd();
        byte[] array = Convert.FromBase64String(str);
        using (System.IO.FileStream fileStream = new FileStream(context.Server.MapPath("~/uploadedimages/") + imageName, FileMode.Create))
        {
            fileStream.Write(array, 0, array.Length);
        }
    }
}

Now let's add a button MainPage.xaml.

<Grid x:Name="LayoutRoot" Background="Blue">
        <Button Content="Browse images" Height="23" HorizontalAlignment="Left" Margin="88,46,0,0" Click="button1_Click" Name="button1" VerticalAlignment="Top" Width="206" />       
        <TextBlock Height="23" Margin="54,73,54,0" Name="textBlock2" VerticalAlignment="Top" Width="292" Foreground="Red" HorizontalAlignment="Center" />
</Grid>

MainPage.xaml.cs

    public partial class MainPage : UserControl
    {
        int totalFilesToUpload = 0;
        int totalFilesUploaded = 0;
        public MainPage()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.textBlock2.Text = string.Empty;
            OpenFileDialog openFIleDialog = new OpenFileDialog();
            openFIleDialog.Filter = "All Image Files ( JPEG,GIF,BMP,PNG)|*.jpg;*.jpeg;*.gif;*.bmp;*.png|JPEG Files ( *.jpg;*.jpeg )|*.jpg;*.jpeg|GIF Files ( *.gif )|*.gif|BMP Files ( *.bmp )|*.bmp|PNG Files ( *.png )|*.png";
            openFIleDialog.FilterIndex = 1;
            openFIleDialog.Multiselect = true;
            string str = string.Empty;
            if (openFIleDialog.ShowDialog() == true)
            {
                foreach (var file in openFIleDialog.Files)
                {
                    using (System.IO.Stream fileStream = GetFileData(file.OpenRead()))
                    {
                        StreamResourceInfo streamResourceFile = new StreamResourceInfo(fileStream, null);
                        byte[] array = new byte[streamResourceFile.Stream.Length];
                        streamResourceFile.Stream.Read(array, 0, (int)streamResourceFile.Stream.Length);
                        str = Convert.ToBase64String(array);
                        WebClient oWebClient = new WebClient();
                        string fileName = Guid.NewGuid().ToString().Replace("-", "") + file.Extension;
                        oWebClient.UploadStringAsync(new Uri("http://localhost:7972/SLFIleUploadUsingHTTPHandler.Web/Handler1.ashx?file=" + fileName), null, str, fileName);
                        oWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(oWebClient_UploadtxtProgressChanged);
                        totalFilesToUpload += 1;
                        str = string.Empty;
                    }
                }
            }
        }
        System.IO.MemoryStream GetFileData(System.IO.Stream oFileStream)
        {
            oFileStream.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] data = new byte[oFileStream.Length];
            oFileStream.Read(data, 0, (int)oFileStream.Length);
            return new System.IO.MemoryStream(data);
        }
        void oWebClient_UploadtxtProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            totalFilesUploaded += 1;
            textBlock2.Text = !string.IsNullOrEmpty(textBlock2.Text) ? (int.Parse(textBlock2.Text) + e.BytesSent).ToString() : e.BytesSent.ToString();
            if (totalFilesUploaded == totalFilesToUpload)
            {             
                textBlock2.Text = totalFilesUploaded + " files uploaded successfully (" + textBlock2.Text + " bytes sent )";
            }
        }
    }

No run the application and click Browse button and select multiple images to upload.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Author
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Uploading File using Generic Handler in Silverlight 4 by Paul On February 14, 2011
Hi Raj, Great article. Currently, I'm using similar method to handle single files. The Uploading works fine. But I get an exception, when I try and Upload a file ( say for e.g. a word .doc file ) which is already open by the Word application. This is causing me a lot of grief. I use file.OpenRead() like in your article. I googled about this issue and there are lot of people having the same issue. I tried some of their suggestions like fileaccess to be set to Read and fileshare to be set as ReadWrite to fix this issue, but nothing worked till now. I thought, you might have come across this problem already, since this is one thing a good QA person would never miss. If you have, pls.you give me some pointers.
Reply | Email | Modify 
Where files are uploaded by Miral On July 22, 2011
Hello your code works fine. Please let us know where file are upload. What changes i need to make if i want to upload same to my web server. Please help me. Thanks
Reply | Email | Modify 
Re: Where files are uploaded by Raj On September 5, 2011
you need to change this folder name "uploadedimages" and put your folder name and location where you want to upload images.
Reply | Email | Modify 
Code is not working by Miral On July 22, 2011
Dear sir, Well code is not working i tried all the steps. Please upload the code. Thanking you, Miral Shah
Reply | Email | Modify 
Re: Code is not working by Raj On September 5, 2011
What error message you getting??
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.