File downloads usually use an attachment to set the Content-disposition value to "attachment;filename=" + filepath in the HTTP response header, and to set the total length of the download file for Content-length (bytes per unit) To achieve.
This article is to use Silverlight to download the file, the service end with the ASP.net general processing program (. ashx) processing.
The following is a project structure chart:
MainPage class source code is as follows:
The code is as follows |
Copy Code |
View Code
Namespace Silverlightdownanduploadfile
{
public delegate void Savefilehandler (int bytesread, byte[] buffer);
public delegate void Uploadfilehandler (int bytesread);
public partial class Mainpage:usercontrol
{
Private SaveFileDialog SFD;
Private OpenFileDialog OFD;
Stream stream = null;
BinaryWriter bw = NULL;
Private long fileLen = 0;
Private long Readfilelen = 0;//download length
Private AutoResetEvent autoevent = new AutoResetEvent (false);
Public MainPage ()
{
InitializeComponent ();
}
#region Download
private void Showdownresult (bool issuccess)
{
This. Dispatcher.begininvoke (
() =>
{
if (issuccess)
MessageBox.Show ("Download completed.");
Else
MessageBox.Show ("Download Error!");
});
}
private void updatedownprogress (int bytesread)
{
Readfilelen + = Bytesread;
Double rate = convert.todouble (Readfilelen)/convert.todouble (FileLen);
Double percent = math.round (Rate, 2) * 100;
downprogress.visibility = visibility.visible;
DownProgress.pgBar.Value = percent;
DownProgress.txtProgress.Text = percent + "%";
}
private void Flushtofile (int bytesread, byte[] buffer)
{
Try
{
if (null = = stream)
{
stream = sfd. OpenFile ();
BW = new BinaryWriter (stream);
}
Bw. Write (buffer, 0, bytesread);
Bw. Flush ();
Updatedownprogress (Bytesread);
Autoevent.set ();
}
catch (Exception ex)
{ }
}
private void Requestanddownfile ()
{
Try
{
HttpWebRequest request = Createwebrequest ("Http://localhost:13953/Download.ashx", "get");
HttpWebRequest webRequest = Request;
Webrequest.begingetresponse (
(asyncresult) =>
{
if (webrequest.haveresponse)
{
Try
{
WebResponse response = Webrequest.endgetresponse (asyncresult)//easy to occur
FileLen = Convert.toint64 (response. headers["Content-length"]);/File length
Stream Responsestream = Response. GetResponseStream ();
int maxbuflength = * 1024;//20k
byte[] buffer = new Byte[maxbuflength];
int bytesread = responsestream.read (buffer, 0, maxbuflength);
while (bytesread!= 0)
{
Dispatcher.begininvoke (New Savefilehandler (Flushtofile), bytesread, buffer);
Autoevent.waitone ();
Buffer = new Byte[maxbuflength];
Bytesread = responsestream.read (buffer, 0, maxbuflength);
}
Showdownresult (TRUE);
}
catch (Exception ex)
{
Showdownresult (FALSE);
}
Finally
{
This. Dispatcher.begininvoke (
() =>
{
if (null!= BW)
Bw. Close ();
if (null!= stream)
Stream. Close ();
});
}
}
}, NULL);
}
catch (Exception ex)
{
Showdownresult (FALSE);
}
}
private void Btndownload_click (object sender, RoutedEventArgs e)
{
FileLen = 0;
Readfilelen = 0;
SFD = new SaveFileDialog ();
SfD. Filter = "(*.rar) |*.rar";
if (SFD. ShowDialog () = = True)
{
Requestanddownfile ();
}
}
private static HttpWebRequest Createwebrequest (String requesturistring, String httpmethod)
{
Try
{
String ticks = Guid.NewGuid (). ToString ();
requestUriString = requesturistring + "/" + ticks;
HttpWebRequest request = (HttpWebRequest) WebRequestCreator.ClientHttp.Create (new Uri (requesturistring));
Request. method = HttpMethod;
return request;
}
catch (Exception ex)
{
return null;
}
}
#endregion
<summary>
The byte array that was actually fetched
</summary>
<param name= "Buffer" ></param>
<param name= "Bytesread" ></param>
<returns></returns>
Private byte[] Getnewbuffer (byte[] buffer, int bytesread)
{
byte[] Newbuffer = new Byte[bytesread];
for (int i = 0; i < bytesread; i++)
{
Newbuffer[i] = Buffer[i];
}
return newbuffer;
}
} |
Download.ashx source code is as follows:
The code is as follows |
Copy Code |
View Code
Namespace Silverlightdownanduploadfile.web
{
<summary>
Summary description of Download
</summary>
public class Download:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Try
{
Context. Response.ContentType = "Text/plain";
Context. Response.Write ("Hello World");
To download a file path
String path = "D:/test.rar"; Context. Server.MapPath ("~/files/lan.txt");
Context. Response.ContentType = Utils.getcontenttype (path);//Set ContentType
Context. Response.appendheader ("Content-disposition", "attachment;filename=" + path);
Context. Response.bufferoutput = false;
Context. Response.Buffer = false;
using (FileStream fs = File.openread (path))
{
BinaryReader br = new BinaryReader (FS);
Long FileLen = br. Basestream.length;
Context. Response.appendheader ("Content-length", filelen.tostring ());
int bytesread = number of bytes read by 0;//
int maxbuflength = * 1024;//20k
byte[] buffer = new Byte[maxbuflength];
Bytesread = Br. Read (buffer, 0, maxbuflength);
while (bytesread!= 0)
{
byte[] Newbuffer = getnewbuffer (buffer, bytesread);
Context. Response.BinaryWrite (Newbuffer);
Context. Response.Flush ();
Buffer = new Byte[maxbuflength];
Bytesread = Br. Read (buffer, 0, maxbuflength);
}
Context. Response.Flush ();
Context. Response.End ();
}
}
catch (Exception ex)
{
}
}
<summary>
The byte array that was actually fetched
</summary>
<param name= "Buffer" ></param>
<param name= "Bytesread" ></param>
<returns></returns>
Private byte[] Getnewbuffer (byte[] buffer, int bytesread)
{
byte[] Newbuffer = new Byte[bytesread];
for (int i = 0; i < bytesread; i++)
{
Newbuffer[i] = Buffer[i];
}
return newbuffer;
}
public bool IsReusable
{
Get
{
return false;
}
}
}
} |
File Upload
File upload through the web, generally to use form form, in Silverlight there is no built-in form form function, reference cattle articles, to achieve Silverlight file upload. As long as the maxRequestLength attribute of the httpruntime node in the Web.config file is large enough, the upload is unrestricted.
Project Structure Chart:
MainPage Type Source code:
The code is as follows |
Copy Code |
View Code
Namespace Silverlightdownanduploadfile
{
public partial class Mainpage:usercontrol
{
Private OpenFileDialog OFD;
Private AutoResetEvent autoevent = new AutoResetEvent (false);
Public MainPage ()
{
InitializeComponent ();
}
private static HttpWebRequest Createwebrequest (String requesturistring, String httpmethod)
{
Try
{
String ticks = Guid.NewGuid (). ToString ();
requestUriString = requesturistring + "/" + ticks;
HttpWebRequest request = (HttpWebRequest) WebRequestCreator.ClientHttp.Create (new Uri (requesturistring));
Request. method = HttpMethod;
return request;
}
catch (Exception ex)
{
return null;
}
}
#region Upload
private void Readfiletorequeststream (BinaryReader fileStream, HttpWebRequest request)
{
Try
{
Request. BeginGetRequestStream ((Requestasyncresult) =>
{
Stream requeststream = null;
Try
{
Requeststream = Request. EndGetRequestStream (Requestasyncresult);
if (null!= requeststream)
{
Silverlightmultipartformdata form = new Silverlightmultipartformdata ();
Form. Addformfield ("Devilfield", "Chinese");
int Maxbufferlen = 25 * 1024;
byte[] buffer = new Byte[maxbufferlen];
int bytesread = filestream.read (buffer, 0, Maxbufferlen);
int i = 0;
while (bytesread!= 0)
{
i++;
byte[] Newbuffer = getnewbuffer (buffer, bytesread);
Form. Addstreamfile ("package" + I, "package" + I, newbuffer);
Buffer = new Byte[maxbufferlen];
Bytesread = filestream.read (buffer, 0, Maxbufferlen);
}
Form. Prepareformdata ()/End
Filestream.close ();
Request. ContentType = "Multipart/form-data; boundary= "+ form. boundary;
foreach (Byte byt in form. Getformdata ())
{
Requeststream.writebyte (BYT);
}
Requeststream.close ();
Autoevent.set ()/Start uploading
}
}
catch (Exception ex)
{ }
Finally
{
if (null!= requeststream)
Requeststream.close ();
if (null!= fileStream)
Filestream.close ();
}
}, NULL);
}
catch (Exception ex)
{
}
}
private void Requestanduploadfile (BinaryReader br)
{
Try
{
if (null = = BR) return;
HttpWebRequest request = Createwebrequest ("Http://localhost:13953/Upload.ashx", "POST");
Readfiletorequeststream (BR, request);
Autoevent.waitone ()//wait stream write complete
Upload
Request. BeginGetResponse (
(asyncresult) =>
{
if (request). Haveresponse)
{
Try
{
WebResponse response = Request. EndGetResponse (asyncresult);
Stream Responsestream = Response. GetResponseStream ();
int bufferlen = 1024;
byte[] buffer = new Byte[bufferlen];
int bytesread = responsestream.read (buffer, 0, Bufferlen);
Responsestream.close ();
String responsetext = System.Text.Encoding.UTF8.GetString (buffer, 0, bytesread);
Showuploadresult (TRUE);
}
catch (Exception ex)
{
Showuploadresult (FALSE);
}
}
}, NULL);
}
catch (Exception ex)
{
Showuploadresult (FALSE);
}
}
private void Btnupload_click (object sender, RoutedEventArgs e)
{
OFD = new OpenFileDialog ();
Ofd. Filter = "(*.rar) |*.rar";
Ofd. MultiSelect = false;
if (OFD. ShowDialog () = = True)
{
uploadprogress.visibility = visibility.visible;
BinaryReader br = new BinaryReader (OFD. File.openread ());
Requestanduploadfile (BR);
}
}
private void Showuploadresult (bool issucess)
{
This. Dispatcher.begininvoke (
() =>
{
uploadprogress.visibility = visibility.collapsed;
if (issucess)
MessageBox.Show ("Upload success");
Else
MessageBox.Show ("Upload failed.");
});
}
#endregion
<summary>
The byte array that was actually fetched
</summary>
<param name= "Buffer" ></param>
<param name= "Bytesread" ></param>
<returns></returns>
Private byte[] Getnewbuffer (byte[] buffer, int bytesread)
{
byte[] Newbuffer = new Byte[bytesread];
for (int i = 0; i < bytesread; i++)
{
Newbuffer[i] = Buffer[i];
}
return newbuffer;
}
}
} |
Upload.ashx File Source:
The code is as follows |
Copy Code |
View Code
Namespace Silverlightdownanduploadfile.web
{
<summary>
Summary description of Upload
</summary>
public class Upload:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
Context. Response.Write ("Hello World");
Stream stream = null;
Try
{
String path = context. Server.MapPath ("~/files/upload.rar");
int i = 0;
while (true)
{
i++;
String packagename = "package" + I;
Httppostedfile UploadFile = context. Request.files[packagename];
if (null!= uploadfile)
{
Stream = context. Request.files[packagename]. InputStream;
FileStream fs = null;
if (i = = 1 && file.exists (path))
{
FS = new FileStream (path, FileMode.Create, FileAccess.Write);
}
Else
{
FS = new FileStream (path, filemode.append, FileAccess.Write);
}
using (BinaryWriter bw = new BinaryWriter (FS))
{
int Maxbufferlen = * 1024;//20k
byte[] buffer = new Byte[maxbufferlen];
int bytesread = stream. Read (buffer, 0, Maxbufferlen);
while (bytesread!= 0)
{
byte[] Newbuff = getnewbuffer (buffer, bytesread);
Bw. Write (newbuff, 0, newbuff.length);
Buffer = new Byte[maxbufferlen];
Bytesread = stream. Read (buffer, 0, Maxbufferlen);
}
Returns the number of bytes uploaded this time
Context. Response.Write (Stream. Length);
Context. Response.Flush ();
}
Stream. Close ();
Fs. Close ();
}
Else
{
if (I!= 1)
Break
Else
i = 0;
}
}
Context. Response.Write ("Upload success!");
Context. Response.Flush ();
Context. Response.End ();
}
catch (Exception ex)
{
}
Finally
{
if (null!= stream)
Stream. Close ();
}
}
<summary>
Gets the byte array that was actually read
</summary>
<param name= "Buffer" ></param>
<param name= "Bytesread" ></param>
<returns></returns>
Private byte[] Getnewbuffer (byte[] buffer, int bytesread)
{
byte[] Newbuffer = new Byte[bytesread];
for (int i = 0; i < bytesread; i++)
{
Newbuffer[i] = Buffer[i];
}
return newbuffer;
}
public bool IsReusable
{
Get
{
return false;
}
}
}
}
|