Silverlight从客户端上传文件到服务器
生活随笔
收集整理的這篇文章主要介紹了
Silverlight从客户端上传文件到服务器
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
這里介紹的是一種利用WebClient手動(dòng)發(fā)送Stream到服務(wù)器頁面的上傳文件方法。
一、服務(wù)器接收文件
這里使用一個(gè)ASHX頁面來接收和保存Silverlight傳來的Stream,頁面代碼如下:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web;namespace Silverlight {/// <summary>/// FileUploadHandler 的摘要說明/// </summary>public class FileUploadHandler : IHttpHandler{public void ProcessRequest(HttpContext context){//獲取上傳參數(shù) - 文件名string fileName = context.Request["FileName"];//獲取上傳的數(shù)據(jù)流using (Stream inputStream = context.Request.InputStream){try{//數(shù)據(jù)緩沖區(qū)byte[] buffer = new byte[4096];int bytesRead = 0;//準(zhǔn)備保存路徑和文件名string filePath = string.Format(@"D:\FileUpload\");//檢查保存路徑是否存在if (!Directory.Exists(filePath)){//不存在進(jìn)行創(chuàng)建Directory.CreateDirectory(filePath);}//準(zhǔn)備寫入文件流using (FileStream fs = File.Create(filePath + fileName, 4096)){//開始循環(huán)寫入文件while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0){//向文件中寫信息fs.Write(buffer, 0, bytesRead);}}//上傳成功context.Response.ContentType = "text/plain";context.Response.Write("上傳成功");}catch (Exception e){//上傳出錯(cuò)context.Response.ContentType = "text/plain";context.Response.Write("上傳失敗, 錯(cuò)誤信息:" + e.Message);}}}public bool IsReusable{get{return false;}}} }這里保存文件的主要流程就是接收上傳參數(shù),準(zhǔn)備保存文件,通過讀取上傳流保存文件內(nèi)容。
二、客戶端發(fā)送文件
客戶端發(fā)送文件使用的是WebClient類。
首先建立一個(gè)WebClient連接:
//準(zhǔn)備上傳連接 WebClient uploadClient = new WebClient(); uploadClient.Headers["Content-Type"] = "multipart/form-data";//連接打開后的操作 uploadClient.OpenWriteCompleted += uploadClient_OpenWriteCompleted; //流寫入完成后的操作 uploadClient.WriteStreamClosed += uploadClient_WriteStreamClosed;//打開上傳連接 uploadClient.OpenWriteAsync(new Uri("", UriKind.Relative), "POST", fileStream);WebClient打開連接后的處理:
void uploadClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) {//將文件數(shù)據(jù)流發(fā)送到服務(wù)器上// e.UserState - 需要上傳的流(客戶端流)using (Stream clientStream = e.UserState as Stream){// e.Result - 目標(biāo)地址的流(服務(wù)端流)using (Stream serverStream = e.Result){byte[] buffer = new byte[4096];int readcount = 0;// clientStream.Read - 將需要上傳的流讀取到指定的字節(jié)數(shù)組中while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0){// serverStream.Write - 將指定的字節(jié)數(shù)組寫入到目標(biāo)地址的流serverStream.Write(buffer, 0, readcount);}}} }WebClient連接關(guān)閉后的處理:
void uploadClient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e) {//判斷寫入是否有異常if (e.Error != null){MessageBox.Show("上傳失敗!", e.Error.Message.ToString());}else{MessageBox.Show("上傳成功!", "文件已保存!");} }客戶端這邊主要就是打開連接,然后打開服務(wù)器的接收流,然后傳輸文件數(shù)據(jù)流到服務(wù)器。
總結(jié)
以上是生活随笔為你收集整理的Silverlight从客户端上传文件到服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode—Best Time t
- 下一篇: Q5.2