I searched a lot of articles and finally barely realized. There are many imperfections.
Create a new directory under the project Pics Copy an image to the root directory.
Image name: Right-click -> Properties -> Generate operation: Resource
UC_UpDown.xaml
<UserControl x:Class="HCLoad.UC_UpDown" xmlns="/winfx/2006/xaml/presentation" xmlns:x="/winfx/2006/xaml" Width="500" Height="500"> <StackPanel Background="White" Height="450"> <Button Content="down" Click="Button_Click"></Button> <HyperlinkButton Content="Download Save" NavigateUri="http://localhost:4528/?fileName=" TargetName="_self" x:Name="lBtnDown" /> <TextBlock x:Name="tbMsgString" Text="Download Progress" TextAlignment="Center" Foreground="Green"></TextBlock> <Button x:Name="btnDownload" Content="DownLoad Pictures" Width="150" Height="35" Margin="15" Click="btnDownload_Click"/> <Border Background="Wheat" BorderThickness="5" Width="400" Height="280"> <Image x:Name="imgDownLoad" Width="400" Height="300" Margin="15" Stretch="Fill"/> </Border> <Button x:Name="btnUpLoad" Content="UpLoad Pictures" Width="150" Height="35" Margin="15" Click="btnUpLoad_Click"/> </StackPanel> </UserControl>
UC_UpDown.
using System; using ; using ; using ; using ; using ; using ; using ; using ; using ; using ; using ; //Because you want to use BitmapImageusing ; //Because you want to use Stream namespace HCLoad { public partial class UC_UpDown : UserControl { //1. The WebClient object can only start one request at a time. If a second request is made before a request is completed (including errors and cancellation), i.e. when IsBusy is true, the second request will throw an exception of type NotSupportedException //2. If the BaseAddress property of the WebClient object is not empty, then BaseAddress and URI (relative address) are combined to form an absolute URI //3. The AllowReadStreamBuffering property of the WebClient class: Whether to buffer data received from Internet resources. The default value is true, caches the data in client memory so that it can be read by the application at any time. //Get selected image information fileinfo; public UC_UpDown() { InitializeComponent(); } #region Download image private void btnDownload_Click(object sender, RoutedEventArgs e) { //Send a download stream data request to the specified URL String imgUrl = "http://localhost:4528/"; Uri endpoint = new Uri(imgUrl); WebClient client = new WebClient(); += new OpenReadCompletedEventHandler(OnOpenReadCompleted); += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged); (endpoint); } void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { // - Is there an error during this asynchronous operation // - Is the asynchronous operation cancelled // - Downloaded Stream type data // - User ID if ( != null) { (()); return; } if ( != true) { //Get the downloaded stream data (image data here) and display it in the picture control //Stream stream = ; //BitmapImage bitmap = new BitmapImage(); //(stream); // = bitmap; Stream clientStream = as Stream; Stream serverStream = (Stream); byte[] buffer = new byte[]; (buffer, 0, ); (buffer, 0, ); (); (); } } void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { // - Percentage of download completion // - The number of bytes currently received // - Total number of bytes to download // - User ID = ("Percent completion:{0} The number of bytes currently received:{1} Data size:{2} ", () + "%", (), ()); } #endregion #region Upload pictures private void btnUpLoad_Click(object sender, RoutedEventArgs e) { /**/ /* * OpenWriteCompleted - Events triggered when opening the stream for uploading completes (including cancellation and errors occur) * WriteStreamClosed - Events triggered when the asynchronous operation of writing data streams is completed (including cancellation operations and when an error occurs) * UploadProgressChanged - Event triggered during uploading data. If OpenWriteAsync() is called, this event will not be triggered * Headers - key/value for the request-related header ** * OpenWriteAsync(Uri address, string method, Object userToken) - Open the stream to write data to the specified URI using the specified method * Uri address - URI that receives uploaded data * string method - HTTP method used (POST or GET) * Object userToken - Data stream that needs to be uploaded */ OpenFileDialog openFileDialog = new OpenFileDialog() { //The Open File dialog box pops up and asks the user to select the image file to open on the local side by themselves Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*", Multiselect = false // Multiple selections are not allowed }; if (() == true)//.) { //fileinfo = ; //Fetch the selected file, where Name is the file name field, and is displayed in the front end as a binding field fileinfo = ; if (fileinfo != null) { WebClient webclient = new WebClient(); string uploadFileName = (); //Get the name of the selected file #region Upload the image to the server Uri upTargetUri = new Uri(("http://localhost:4528/?fileName={0}", uploadFileName), ); //Specify the upload address += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted); ["Content-Type"] = "multipart/form-data"; (upTargetUri, "POST", ()); += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed); #endregion } else { ("Please select the picture you want to upload!!!"); } } } void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) { //Send the image data stream to the server // - The stream that needs to be uploaded (client stream) Stream clientStream = as Stream; // - The flow of the destination address (server side stream) Stream serverStream = ; byte[] buffer = new byte[4096]; int readcount = 0; // - Read the stream that needs to be uploaded into the specified byte array while ((readcount = (buffer, 0, )) > 0) { // - Write the specified byte array to the stream at the destination address (buffer, 0, readcount); } (); (); } void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e) { //Judge whether there is any abnormality in writing if ( != null) { (()); } else { ("The picture upload was successful!!!"); } } #endregion private void Button_Click(object sender, RoutedEventArgs e) { //This method cannot be handled, as if it prompts cross-domain operation. //Tip: Error: Unhandled Error in Silverlight Application Cross-thread access is invalid. //Uri upTargetUri = new Uri(("http://localhost:4528/?filename={0}", ""), ); //Specify the upload address //WebRequest request = (upTargetUri); // = "GET"; // = "application/octet-stream"; //(new AsyncCallback(RequestReady), request); //Download by calling js code, it is relatively simple. ("='http://localhost:4528/?filename=';"); } void RequestReady(IAsyncResult asyncResult) { ("RequestComplete"); } } }
Create a new project
using System; using ; using ; using ; using ; //Because you need to use Stream namespace { public class WebClientUpLoadStreamHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { //Get the uploaded data stream string fileNameStr = ["fileName"]; Stream sr = ; try { string filename = ""; filename = fileNameStr; byte[] buffer = new byte[4096]; int bytesRead = 0; //Write the current data stream to the server folder ClientBin string targetPath = ("Pics/" + filename + ".jpg"); using (FileStream fs = (targetPath, 4096)) { while ((bytesRead = (buffer, 0, )) > 0) { //Write information to the file (buffer, 0, bytesRead); } } = "text/plain"; ("Uploaded successfully"); } catch (Exception e) { = "text/plain"; ("Upload failed, error message:" + ); } finally { (); } } public bool IsReusable { get { return false; } } } }
New
using System; using ; using ; using ; using ; using ; namespace { /// <summary> /// Summary description of $codebehindclassname$ /// </summary> public class download : IHttpHandler { private long ChunkSize = 102400;//100K Each time you read the file, only 100K is read, which can relieve the pressure on the server. public void ProcessRequest(HttpContext context) { //string fileName = "";//The file name saved by the client String fileName = ["filename"]; string filePath = (""); fileInfo = new (filePath); if ( == true) { byte[] buffer = new byte[ChunkSize]; (); iStream = (filePath); long dataLengthToRead = ;//Get the total size of the downloaded file = "application/octet-stream"; //Notify the browser to download the file instead of opening it ("Content-Disposition", "attachment; filename=" + (fileName, .UTF8)); while (dataLengthToRead > 0 && ) { int lengthRead = (buffer, 0, Convert.ToInt32(ChunkSize));//Read size (buffer, 0, lengthRead); (); dataLengthToRead = dataLengthToRead - lengthRead; } (); (); } // = "text/plain"; //("Hello World"); } public bool IsReusable { get { return false; } } } }
refer to:
/wsdj-ittech/archive/2009/08/26/
/wsdj-ittech/archive/2009/08/25/
/wmt1708/archive/2009/03/07/
/u/20090918/10/
/wsdj-ittech/archive/2009/08/25/
/gwazy/archive/2009/04/02/
/ewyb/archive/2009/12/10/
/emily1900/archive/2010/06/08/