Thursday, 1 March 2012

Upload file in Silverlight


Create ashx file to Web Application and add below code. Store this file where client bin folder is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace UtilizationReport.Web
{
    /// <summary>
    /// Summary description for FileUpload
    /// </summary>
    public class FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string filename = context.Request.QueryString["filename"].ToString();
            using (FileStream fs = File.Create(context.Server.MapPath("~/UtilizationReport/"+filename)))
            {
                SaveFile(context.Request.InputStream, fs);
            }
        }

        private void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

From Silverlight application when you open a dialog box:

private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "All files|*.xls";
            dlg.Multiselect = false;

            if ((bool)dlg.ShowDialog())
            {
               UploadFile.UploadFiles(dlg.File.Name, dlg.File.OpenRead());
                txtSdataStatus.Text = "File uploaded successfully!";
            }
        }

In Silverlight application create class that will read file and convert to binary and send to ashx file which will save it:

public static class UploadFile
    {
        public static void UploadFiles(string filename, Stream data)
        {
            UriBuilder ub = new UriBuilder(App.Current.Host.Source.AbsoluteUri.Replace("ClientBin/YourFile.xap", "") + "FileUpload.ashx");
            ub.Query = string.Format("filename={0}", filename);
            WebClient client = new WebClient();
            client.OpenWriteCompleted += (sender, e) =>
            {
                pushdata(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            client.OpenWriteAsync(ub.Uri);
        }

       public static void pushdata(Stream input, Stream output)
        {
            byte[] buffer = new byte[20000];
            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }
    }

To Upload heavy files update web.config:
   <httpRuntime maxRequestLength="2097151" />