通過web進行檔上傳,一般要使用form表單,在silverlight裡面沒有內置form表單功能,參考牛人文章,實現Silverlight檔上傳。只要Web.config檔中HTTPRuntime節點的maxRequestLength屬性足夠大,上傳就不受限制。
專案結構圖:

1042514063-0  

MainPage類源碼:
View Code
1 namespace SilverlightDownAndUploadFile
2 {
3 public partial class MainPage : UserControl
4 {
5 private OpenFileDialog ofd;
6 private AutoResetEvent autoEvent = new AutoResetEvent(false);
7
8 public MainPage()
9 {
10 InitializeComponent();
11 }
12
13 private static HttpWebRequest CreateWebRequest(string requestUriString, string HTTPMethod)
14 {
15 try
16 {
17 string ticks = Guid.NewGuid().ToString();
18 requestUriString = requestUriString + "/" + ticks;
19 HttpWebRequest request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(requestUriString));
20 request.Method = HTTPMethod;
21
22 return request;
23 }
24 catch (Exception ex)
25 {
26 return null;
27 }
28 }
29 #region 上傳
30
31 private void ReadFileToRequestStream(BinaryReader fileStream, HttpWebRequest request)
32 {
33 try
34 {
35 request.BeginGetRequestStream((requestAsyncResult) =>
36 {
37 Stream requestStream = null;
38 try
39 {
40 requestStream = request.EndGetRequestStream(requestAsyncResult);
41 if (null != requestStream)
42 {
43 SilverlightMultipartFormData form = new SilverlightMultipartFormData();
44 //form.AddFormField("devilField", "中國人");
45 int maxBufferLen = 25 * 1024;
46 byte[] buffer = new byte[maxBufferLen];
47 int bytesRead = fileStream.Read(buffer, 0, maxBufferLen);
48 int i = 0;
49 while (bytesRead != 0)
50 {
51 i++;
52 byte[] newBuffer = GetNewBuffer(buffer, bytesRead);
53 form.AddStreamFile("package" + i, "package" + i, newBuffer);
54 buffer = new byte[maxBufferLen];
55 bytesRead = fileStream.Read(buffer, 0, maxBufferLen);
56 }
57
58 form.PrepareFormData();//結束
59 fileStream.Close();
60 request.ContentType = "multipart/form-data; boundary=" + form.Boundary;
61 foreach (byte byt in form.GetFormData())
62 {
63 requestStream.WriteByte(byt);
64 }
65 requestStream.Close();
66 autoEvent.Set();//開始上傳
67 }
68 }
69 catch (Exception ex)
70 { }
71 finally
72 {
73 if (null != requestStream)
74 requestStream.Close();
75 if (null != fileStream)
76 fileStream.Close();
77 }
78 }, null);
79 }
80 catch (Exception ex)
81 {
82
83 }
84 }
85
86 private void RequestAndUploadFile(BinaryReader br)
87 {
88 try
89 {
90 if (null == br) return;
91 HttpWebRequest request = CreateWebRequest("HTTP://localhost:13953/Upload.ashx", "POST");
92 ReadFileToRequestStream(br, request);
93 autoEvent.WaitOne();//等待流寫入完畢
94
95 //上傳
96 request.BeginGetResponse(
97 (asyncResult) =>
98 {
99 if (request.HaveResponse)
100 {
101 try
102 {
103 WebResponse response = request.EndGetResponse(asyncResult);
104
105 Stream responseStream = response.GetResponseStream();
106 int bufferLen = 1024;
107 byte[] buffer = new byte[bufferLen];
108 int bytesRead = responseStream.Read(buffer, 0, bufferLen);
109 responseStream.Close();
110
111 string responseText = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
112
113 ShowUploadResult(true);
114 }
115 catch (Exception ex)
116 {
117 ShowUploadResult(false);
118 }
119 }
120 }, null);
121 }
122 catch (Exception ex)
123 {
124 ShowUploadResult(false);
125 }
126 }
127
128 private void btnUpload_Click(object sender, RoutedEventArgs e)
129 {
130 ofd = new OpenFileDialog();
131 ofd.Filter = "(*.rar)|*.rar";
132 ofd.Multiselect = false;
133
134 if (ofd.ShowDialog() == true)
135 {
136 uploadProgress.Visibility = Visibility.Visible;
137 BinaryReader br = new BinaryReader(ofd.File.OpenRead());
138 RequestAndUploadFile(br);
139 }
140 }
141
142 private void ShowUploadResult(bool isSucess)
143 {
144 this.Dispatcher.BeginInvoke(
145 () =>
146 {
147 uploadProgress.Visibility = Visibility.Collapsed;
148 if (isSucess)
149 MessageBox.Show("上傳成功");
150 else
151 MessageBox.Show("上傳失敗.");
152 });
153 }
154 #endregion
155
156 /// <summary>
157 /// 獲了實際接讀取到的位元組陣列
158 /// </summary>
159 /// <param name="buffer"></param>
160 /// <param name="bytesRead"></param>
161 /// <returns></returns>
162 private byte[] GetNewBuffer(byte[] buffer, int bytesRead)
163 {
164 byte[] newBuffer = new byte[bytesRead];
165 for (int i = 0; i < bytesRead; i++)
166 {
167 newBuffer[i] = buffer[i];
168 }
169 return newBuffer;
170 }
171 }
172 }
Upload.ashx檔源碼:
View Code

1 namespace SilverlightDownAndUploadFile.Web
2 {
3 /// <summary>
4 /// Upload 的摘要說明
5 /// </summary>
6 public class Upload : IHttpHandler
7 {
8
9 public void ProcessRequest(HttpCoNtext coNtext)
10 {
11 //coNtext.Response.ContentType = "text/plain";
12 //coNtext.Response.Write("Hello World");
13 Stream stream = null;
14 try
15 {
16 string path = coNtext.Server.MapPath("~/Files/upload.rar");
17 int i = 0;
18 while (true)
19 {
20 i++;
21 string packageName = "package" + i;
22 HttpPostedFile uploadFile = coNtext.Request.Files[packageName];
23 if (null != uploadFile)
24 {
25 stream = coNtext.Request.Files[packageName].InputStream;
26 FileStream fs = null;
27 if (i == 1 && File.Exists(path))
28 {
29 fs = new FileStream(path, FileMode.Create, FileAccess.Write);
30 }
31 else
32 {
33 fs = new FileStream(path, FileMode.Append, FileAccess.Write);
34 }
35
36 using (BinaryWriter bw = new BinaryWriter(fs))
37 {
38 int maxBufferLen = 20 * 1024;//20K
39 byte[] buffer = new byte[maxBufferLen];
40 int bytesRead = stream.Read(buffer, 0, maxBufferLen);
41 while (bytesRead != 0)
42 {
43 byte[] newBuff = GetNewBuffer(buffer, bytesRead);
44 bw.Write(newBuff, 0, newBuff.Length);
45
46 buffer = new byte[maxBufferLen];
47 bytesRead = stream.Read(buffer, 0, maxBufferLen);
48 }
49
50 //返回本次上傳位元組數
51 coNtext.Response.Write(stream.Length);
52 coNtext.Response.Flush();
53 }
54
55 stream.Close();
56 fs.Close();
57 }
58 else
59 {
60 if (i != 1)
61 break;
62 else
63 i = 0;
64 }
65 }
66
67 coNtext.Response.Write("Upload Success!");
68 coNtext.Response.Flush();
69 coNtext.Response.End();
70 }
71 catch (Exception ex)
72 {
73 }
74 finally
75 {
76 if (null != stream)
77 stream.Close();
78 }
79 }
80
81 /// <summary>
82 /// 獲取實際讀取到的位元組陣列
83 /// </summary>
84 /// <param name="buffer"></param>
85 /// <param name="bytesRead"></param>
86 /// <returns></returns>
87 private byte[] GetNewBuffer(byte[] buffer, int bytesRead)
88 {
89 byte[] newBuffer = new byte[bytesRead];
90 for (int i = 0; i < bytesRead; i++)
91 {
92 newBuffer[i] = buffer[i];
93 }
94 return newBuffer;
95 }
96
97 public bool IsReusable
98 {
99 get
100 {
101 return false;
102 }
103 }
104 }
105 }
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()