Download multiple files in silverlight 4

I am trying to implement a multi-user file loader in silverlight 4. The silverlight control contains only one button. when you click on it, OpenFileDialog is displayed, and they can select multiple files. as soon as they close the dialog, the FileInfo object for all the files they have selected is added to the list. then in my web form I have a javascript button that, when clicked, calls a method in the silverlight control to cycle through the list and upload files. this method returns a string containing virtual paths to all downloaded files, separated by a semicolon. Then I can use this line to add paths to all images to the database in C # code.

the file is loaded by calling the OpenRead () method of the FileInfo object to get the stream containing the bytes of the file, creating the WebClient object and calling the OpenWriteAsync method, passing the HTTP handler URI on my website. The OpenWriteCompleted Web Client event is configured to write a stream of a FileInfo object to the output stream.

The HTTP handler reads bytes from the request stream and saves them to a file using FileStream.

Here is the code for the silverlight control:

public partial class MainPage : UserControl
{
    private List<FileInfo> files = new List<FileInfo>();
    private String handlerUrl;
    private String imageBin;

    public MainPage(string handlerUrl, string imageBin)
    {
        InitializeComponent();

        this.handlerUrl = handlerUrl;
        this.imageBin = imageBin;

        if (!(this.imageBin.EndsWith("/")))
            this.imageBin += "/";

        //register control as scriptable object to allow methods to be called from javascript
        HtmlPage.RegisterScriptableObject("SilverlightCode", this);
    }

    private void btnBrowse_Click(object sender, RoutedEventArgs e)
    {
        files.Clear();

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Multiselect = true;

        bool? showDialog = ofd.ShowDialog();

        if ((showDialog != null) && (showDialog.Value))
        {
            try
            {
                foreach (FileInfo fi in ofd.Files)
                {
                    //check file is valid image file
                    BitmapImage source = new BitmapImage();
                    source.SetSource(fi.OpenRead());

                    files.Add(fi);
                }
            }
            catch
            {
                txtBrowse.Text = "Invalid image file selected.";
                files.Clear();
                return;
            }
        }

        if (files.Count == 1)
            txtBrowse.Text = "1 image selected.";
        else
            txtBrowse.Text = files.Count.ToString() + " images selected.";
    }

    [ScriptableMember]
    public string UploadImages()
    {
        try
        {
            String s = "";
            String now = DateTime.Now.ToString("yyyyMMddHHmmss");

            for (int i = 0; i < files.Count; i++)
            {
                String filename = imageBin + now + i.ToString("00000") + files[i].Extension;
                s += filename + "; ";

                UploadImage(files[i], filename, i);
            }

            return s.Trim();
        }
        catch
        {
            return "";
        }
    }

    private void UploadImage(FileInfo imageFile, String uploadImageVirtualPath, int index)
    {
        UriBuilder ub = new UriBuilder(handlerUrl);
        ub.Query = String.Format("filename={0}", uploadImageVirtualPath);

        Stream stream = imageFile.OpenRead();

        WebClient client = new WebClient();

        client.OpenWriteCompleted += (sender, e) =>
        {
            PushData(stream, e.Result);
            e.Result.Close();
            stream.Close();
        };

        client.OpenWriteAsync(ub.Uri);
    }

    private static void PushData(Stream input, Stream output)
    {
        byte[] buffer = new byte[input.Length];
        input.Read(buffer, 0, buffer.Length);
        output.Write(buffer, 0, buffer.Length);
    }
}

and here is the code for the HTTP handler:

public class ImagesHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //process request
        string filename = context.Request.QueryString["filename"].ToString();

        using (FileStream fs = File.Create(context.Server.MapPath(filename)))
        {
            SaveFile(context.Request.InputStream, fs);
        }
    }

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

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

, , , HTTP , , . , , , , , , , . , HTTP . , silverlight ( , , , :-)).

2 ,

+3
1

: -

    using (FileStream fs = File.Create(context.Server.MapPath(filename)))  
    {
         SaveFile(context.Request.InputStream, fs);
         fs.Flush();
    }

, .

, , -, . , - "runthisevilstuff.ashx" . .

0

All Articles