Handler. ashx
Code
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. Services;
Using System. IO;
Namespace Silverlightupfile. Web
{
/// <Summary>
/// $ Codebehindclassname $ abstract description
/// </Summary>
[WebService (namespace = " Http://tempuri.org/ " )]
[Webservicebinding (conformsto = Wsiprofiles. basicprofile1_1)]
Public Class Handler: ihttphandler
{
Public Void Processrequest (httpcontext context)
{ // Obtain the uploaded data stream
Stream SR = Context. Request. inputstream;
Try
{
// Generate a random file name (the name of the uploaded image in this demo can also be passed through the parameter method)
String Chars = " Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz " ;
Random RND = New Random ();
String Filename = "" ;
For ( Int I = 1 ; I <= 32 ; I ++ )
{
Filename + = Chars. substring (RND. Next (chars. length ), 1 );
}
Byte [] Buffer = New Byte [ 4096 ];
Int Bytesread = 0 ;
// Write the current data stream to the client folder clientbin.
Using (Filestream FS = File. Create (context. server. mappath ( " Clientbin/ " + Filename + " . Jpg " ), 4096 ))
{
While (Bytesread = Sr. Read (buffer, 0 , Buffer. Length )) > 0 )
{
// Write information to a file
FS. Write (buffer, 0 , Bytesread );
}
}
Context. response. contenttype = " Text/plain " ;
Context. response. Write ( " Uploaded " );
}
Catch (Exception E)
{
Context. response. contenttype = " Text/plain " ;
Context. response. Write ( " Upload Failed. error message: " + E. Message );
}
Finally
{
Sr. Dispose ();
}
}
Public BoolIsreusable
{
Get
{
Return False;
}
}
}
}
Code
Private Void Onuploadclick ( Object Sender, routedeventargs E)
{
Openfiledialog = New Openfiledialog ()
{
Filter = " JPEG files (*. jpg) | *. jpg | all files (*. *) | *.* " ,
Multiselect = True
};
If (( Bool ) (Openfiledialog. showdialog ()))
{
Fi = Openfiledialog. file;
WebClient = New WebClient ();
WebClient. openwritecompleted += New openwritecompletedeventhandler (webclient_openwritecompleted);
WebClient. openwriteasync ( New uri ( " HTTP: // localhost: 3239/handler. ashx " , urikind. absolute), " post " );
}
}
Code
< Usercontrol X: Class = "Silverlightupfile. Page"
Xmlns = "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "Http://schemas.microsoft.com/winfx/2006/xaml"
Width = "400" Height = "300" >
< Grid X: Name = "Layoutroot" Background = "White" >
< Image X: Name = "Myimage" Grid. Column = "1" />
< Stackpanel Grid. Row = "1" Background = "White" Grid. columnspan = "2" Orientation = "Horizontal" Horizontalalignment = "Stretch" >
< Button Grid. Row = "1"
Grid. Column = "0"
Content = "Select image"
Margin = "8" Click = "Onclick" Fontsize = "16" Width = "100" Height = "30" />
< Button Grid. Row = "1"
Grid. Column = "2"
Content = "Upload this image"
Margin = "8" Click = "Onuploadclick" Fontsize = "16" Width = "100" Height = "30" />
</ Stackpanel >
</ Grid >
</ Usercontrol >