Asp.Net模擬表單提交數(shù)據(jù)和上傳文件的實現(xiàn)代碼
來源:易賢網(wǎng) 閱讀:2540 次 日期:2014-08-15 15:05:22
溫馨提示:易賢網(wǎng)小編為您整理了“Asp.Net模擬表單提交數(shù)據(jù)和上傳文件的實現(xiàn)代碼”,方便廣大網(wǎng)友查閱!

如果你需要跨域上傳內(nèi)容到另外一個域名并且需要獲取返回值,使用Asp.Net的作為代理是最好的辦法,要是客戶端直接提交到iframe中,由于跨域是無法用javascript獲取到iframe中返回的內(nèi)容的。此時需要在自己的網(wǎng)站做一個動態(tài)頁作為代理,將表單提交到動態(tài)頁,動態(tài)頁負(fù)責(zé)將表單的內(nèi)容使用WebClient或HttpWebRequest將表單數(shù)據(jù)再上傳到遠(yuǎn)程服務(wù)器,由于在服務(wù)器端進(jìn)行操作,就不存在跨域問題了。

WebClient上傳只包含鍵值對的文本信息示例代碼:

代碼如下:

string uriString = "http://localhost/login.aspx";

// 創(chuàng)建一個新的 WebClient 實例.

WebClient myWebClient = new WebClient();

string postData = "Username=admin&Password=admin";

// 注意這種拼字符串的ContentType

myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

// 轉(zhuǎn)化成二進(jìn)制數(shù)組

byte[] byteArray = Encoding.ASCII.GetBytes(postData);

// 上傳數(shù)據(jù),并獲取返回的二進(jìn)制數(shù)據(jù).

byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);

WebClient上傳只包含文件的示例代碼:

代碼如下:

String uriString = "http://localhost/uploadFile.aspx";

// 創(chuàng)建一個新的 WebClient 實例.

WebClient myWebClient = new WebClient();

string fileName = @"C:/upload.txt";

// 直接上傳,并獲取返回的二進(jìn)制數(shù)據(jù).

byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);

 對于既包含文件又包含文本鍵值對信息的示例代碼,需要構(gòu)造表單提交的內(nèi)容,對于學(xué)asp的同學(xué)來說,下面的表單提交內(nèi)容一定不會陌生

代碼如下:

-----------------------------7d429871607fe

Content-Disposition: form-data; name="file1"; filename="G:/homepage.txt"

Content-Type: text/plain

易賢網(wǎng):http://bhx05.cn

-----------------------------7d429871607fe

Content-Disposition: form-data; name="filename"

default filename

-----------------------------7d429871607fe--

所以只要拼一個這樣的byte[] data數(shù)據(jù)Post過去,就可以達(dá)到同樣的效果了。但是一定要注意,對于這種帶有文件上傳的,其ContentType是不一樣的,例如上面的這種,其ContentType為"multipart/form-data; boundary=---------------------------7d429871607fe"。有了ContentType,我們就可以知道boundary(就是上面的"---------------------------7d429871607fe"),知道boundary了我們就可以構(gòu)造出我們所需要的byte[] data了,最后,不要忘記,把我們構(gòu)造的ContentType傳到WebClient中(例如:webClient.Headers.Add("Content-Type", ContentType);)這樣,就可以通過WebClient.UploadData 方法上載文件數(shù)據(jù)了。

001 using System;

002 using System.Web;

003 using System.IO;

004 using System.Net;

005 using System.Text;

006 using System.Collections;

007 namespace UploadData.Common

008 {

009 public class CreateBytes

010 {

011 Encoding encoding = Encoding.UTF8;

012 public byte[] JoinBytes(ArrayList byteArrays)

013 {

014 int length = 0;

015 int readLength = 0;

016 // 加上結(jié)束邊界

017 string endBoundary = Boundary + "-- ";

018 byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);

019 byteArrays.Add(endBoundaryBytes);

020 foreach (byte[] b in byteArrays)

021 {

022 length += b.Length;

023 }

024 byte[] bytes = new byte[length];

025 // 遍歷復(fù)制

026 foreach (byte[] b in byteArrays)

027 {

028 b.CopyTo(bytes, readLength);

029 readLength += b.Length;

030 }

031 return bytes;

032 }

033 public bool UploadData(string uploadUrl, byte[] bytes, out byte[] responseBytes)

034 {

035 WebClient webClient = new WebClient();

036 webClient.Headers.Add("Content-Type", ContentType);

037 try

038 {

039 responseBytes = webClient.UploadData(uploadUrl, bytes);

040 return true;

041 }

042 catch (WebException ex)

043 {

044 Stream resp = ex.Response.GetResponseStream();

045 responseBytes = new byte[ex.Response.ContentLength];

046 resp.Read(responseBytes, 0, responseBytes.Length);

047 }

048 return false;

049 }

050 /// 獲取普通表單區(qū)域二進(jìn)制數(shù)組

051 public byte[] CreateFieldData(string fieldName, string fieldValue)

052 {

053 string textTemplate = Boundary + " Content-Disposition: form-data; name="{0}" {1} ";

054 string text = String.Format(textTemplate, fieldName, fieldValue);

055 byte[] bytes = encoding.GetBytes(text);

056 return bytes;

057 }

058 public byte[] CreateFieldData(string fieldName, string filename, string contentType, byte[] fileBytes)

059 {

060 string end = " ";

061 string textTemplate = Boundary + " Content-Disposition: form-data; name="{0}"; filename="{1}" Content-Type: {2} ";

062 // 頭數(shù)據(jù)

063 string data = String.Format(textTemplate, fieldName, filename, contentType);

064 byte[] bytes = encoding.GetBytes(data);

065 // 尾數(shù)據(jù)

066 byte[] endBytes = encoding.GetBytes(end);

067 // 合成后的數(shù)組

068 byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];

069 bytes.CopyTo(fieldData, 0); // 頭數(shù)據(jù)

070 fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二進(jìn)制數(shù)據(jù)

071 endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); //

072 return fieldData;

073 }

074 public string Boundary

075 {

076 get

077 {

078 string[] bArray, ctArray;

079 string contentType = ContentType;

080 ctArray = contentType.Split(';');

081 if (ctArray[0].Trim().ToLower() == "multipart/form-data")

082 {

083 bArray = ctArray[1].Split('=');

084 return "--" + bArray[1];

085 }

086 return null;

087 }

088 }

089 public string ContentType

090 {

091 get

092 {

093 if (HttpContext.Current == null)

094 {

095 return "multipart/form-data; boundary=---------------------------7d5b915500cee";

096 }

097 return HttpContext.Current.Request.ContentType;

098 }

099 }

100 }

101 }

102 using System;

103 using System.Drawing;

104 using System.Collections;

105 using System.ComponentModel;

106 using System.Windows.Forms;

107 using System.Data;

108 using UploadData.Common;

109 using System.IO;

110 namespace UploadDataWin

111 {

112 public class frmUpload : System.Windows.Forms.Form

113 {

114 private System.Windows.Forms.Label lblAmigoToken;

115 private System.Windows.Forms.TextBox txtAmigoToken;

116 private System.Windows.Forms.Label lblFilename;

117 private System.Windows.Forms.TextBox txtFilename;

118 private System.Windows.Forms.Button btnBrowse;

119 private System.Windows.Forms.TextBox txtFileData;

120 private System.Windows.Forms.Label lblFileData;

121 private System.Windows.Forms.Button btnUpload;

122 private System.Windows.Forms.OpenFileDialog openFileDialog1;

123 private System.Windows.Forms.TextBox txtResponse;

124 private System.ComponentModel.Container components = null;

125 public frmUpload()

126 {

127 InitializeComponent();

128 }

129 protected override void Dispose(bool disposing)

130 {

131 if (disposing)

132 {

133 if (components != null)

134 {

135 components.Dispose();

136 }

137 }

138 base.Dispose(disposing);

139 }

140 private void InitializeComponent()

141 {

142 this.lblAmigoToken = new System.Windows.Forms.Label();

143 this.txtAmigoToken = new System.Windows.Forms.TextBox();

144 this.lblFilename = new System.Windows.Forms.Label();

145 this.txtFilename = new System.Windows.Forms.TextBox();

146 this.btnBrowse = new System.Windows.Forms.Button();

147 this.txtFileData = new System.Windows.Forms.TextBox();

148 this.lblFileData = new System.Windows.Forms.Label();

149 this.btnUpload = new System.Windows.Forms.Button();

150 this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();

151 this.txtResponse = new System.Windows.Forms.TextBox();

152 this.SuspendLayout();

153 //

154 // lblAmigoToken

155 //

156 this.lblAmigoToken.Location = new System.Drawing.Point(40, 48);

157 this.lblAmigoToken.Name = "lblAmigoToken";

158 this.lblAmigoToken.Size = new System.Drawing.Size(72, 23);

159 this.lblAmigoToken.TabIndex = 0;

160 this.lblAmigoToken.Text = "AmigoToken";

161 //

162 // txtAmigoToken

163 //

164 this.txtAmigoToken.Location = new System.Drawing.Point(120, 48);

165 this.txtAmigoToken.Name = "txtAmigoToken";

166 this.txtAmigoToken.Size = new System.Drawing.Size(248, 21);

167 this.txtAmigoToken.TabIndex = 1;

168 this.txtAmigoToken.Text = "";

169 //

170 // lblFilename

171 //

172 this.lblFilename.Location = new System.Drawing.Point(40, 96);

173 this.lblFilename.Name = "lblFilename";

174 this.lblFilename.Size = new System.Drawing.Size(80, 23);

175 this.lblFilename.TabIndex = 2;

176 this.lblFilename.Text = "Filename";

177 //

178 // txtFilename

179 //

180 this.txtFilename.Location = new System.Drawing.Point(120, 96);

181 this.txtFilename.Name = "txtFilename";

182 this.txtFilename.Size = new System.Drawing.Size(248, 21);

183 this.txtFilename.TabIndex = 3;

184 this.txtFilename.Text = "";

185 //

186 // btnBrowse

187 //

188 this.btnBrowse.Location = new System.Drawing.Point(296, 144);

189 this.btnBrowse.Name = "btnBrowse";

190 this.btnBrowse.TabIndex = 4;

191 this.btnBrowse.Text = "瀏覽";

192 this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);

193 //

194 // txtFileData

195 //

196 this.txtFileData.Location = new System.Drawing.Point(120, 144);

197 this.txtFileData.Name = "txtFileData";

198 this.txtFileData.Size = new System.Drawing.Size(168, 21);

199 this.txtFileData.TabIndex = 5;

200 this.txtFileData.Text = "";

201 //

202 // lblFileData

203 //

204 this.lblFileData.Location = new System.Drawing.Point(40, 144);

205 this.lblFileData.Name = "lblFileData";

206 this.lblFileData.Size = new System.Drawing.Size(72, 23);

207 this.lblFileData.TabIndex = 6;

208 this.lblFileData.Text = "FileData";

209 //

210 // btnUpload

211 //

212 this.btnUpload.Location = new System.Drawing.Point(48, 184);

213 this.btnUpload.Name = "btnUpload";

214 this.btnUpload.TabIndex = 7;

215 this.btnUpload.Text = "Upload";

216 this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);

217 //

218 // txtResponse

219 //

220 this.txtResponse.Location = new System.Drawing.Point(136, 184);

221 this.txtResponse.Multiline = true;

222 this.txtResponse.Name = "txtResponse";

223 this.txtResponse.Size = new System.Drawing.Size(248, 72);

224 this.txtResponse.TabIndex = 8;

225 this.txtResponse.Text = "";

226 //

227 // frmUpload

228 //

229 this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

230 this.ClientSize = new System.Drawing.Size(400, 269);

231 this.Controls.Add(this.txtResponse);

232 this.Controls.Add(this.btnUpload);

233 this.Controls.Add(this.lblFileData);

234 this.Controls.Add(this.txtFileData);

235 this.Controls.Add(this.btnBrowse);

236 this.Controls.Add(this.txtFilename);

237 this.Controls.Add(this.lblFilename);

238 this.Controls.Add(this.txtAmigoToken);

239 this.Controls.Add(this.lblAmigoToken);

240 this.Name = "frmUpload";

241 this.Text = "frmUpload";

242 this.ResumeLayout(false);

243 }

244 [STAThread]

245 static void Main()

246 {

247 Application.Run(new frmUpload());

248 }

249 private void btnUpload_Click(object sender, System.EventArgs e)

250 {

251 // 非空檢驗

252 if (txtAmigoToken.Text.Trim() == "" || txtFilename.Text == "" || txtFileData.Text.Trim() == "")

253 {

254 MessageBox.Show("Please fill data");

255 return;

256 }

257 // 所要上傳的文件路徑

258 string path = txtFileData.Text.Trim();

259 // 檢查文件是否存在

260 if (!File.Exists(path))

261 {

262 MessageBox.Show("{0} does not exist!", path);

263 return;

264 }

265 // 讀文件流

266 FileStream fs = new FileStream(path, FileMode.Open,

267 FileAccess.Read, FileShare.Read);

268 // 這部分需要完善

269 string ContentType = "application/octet-stream";

270 byte[] fileBytes = new byte[fs.Length];

271 fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));

272 // 生成需要上傳的二進(jìn)制數(shù)組

273 CreateBytes cb = new CreateBytes();

274 // 所有表單數(shù)據(jù)

275 ArrayList bytesArray = new ArrayList();

276 // 普通表單

277 bytesArray.Add(cb.CreateFieldData("FileName", txtFilename.Text));

278 bytesArray.Add(cb.CreateFieldData("AmigoToken", txtAmigoToken.Text));

279 // 文件表單

280 bytesArray.Add(cb.CreateFieldData("FileData", path

281 , ContentType, fileBytes));

282 // 合成所有表單并生成二進(jìn)制數(shù)組

283 byte[] bytes = cb.JoinBytes(bytesArray);

284 // 返回的內(nèi)容

285 byte[] responseBytes;

286 // 上傳到指定Url

287 bool uploaded = cb.UploadData("http://localhost/UploadData/UploadAvatar.aspx", bytes, out responseBytes);

288 // 將返回的內(nèi)容輸出到文件

289 using (FileStream file = new FileStream(@"c: esponse.text", FileMode.Create, FileAccess.Write, FileShare.Read))

290 {

291 file.Write(responseBytes, 0, responseBytes.Length);

292 }

293 txtResponse.Text = System.Text.Encoding.UTF8.GetString(responseBytes);

294 }

295 private void btnBrowse_Click(object sender, System.EventArgs e)

296 {

297 if (openFileDialog1.ShowDialog() == DialogResult.OK)

298 {

299 txtFileData.Text = openFileDialog1.FileName;

300 }

301 }

302 }

303 }

更多信息請查看IT技術(shù)專欄

更多信息請查看網(wǎng)絡(luò)編程
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機(jī)號
  • 驗證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報警專用圖標(biāo)