如果你需要跨域上传内容到另外一个域名并且需要获取返回值,使用Asp.Net的作为代理是最好的办法,要是客户端直接提交到iframe中,由于跨域是无法用javascript获取到iframe中返回的内容的。此时需要在自己的网站做一个动态页作为代理,将表单提交到动态页,动态页负责将表单的内容使用WebClient或HttpWebRequest将表单数据再上传到远程服务器,由于在服务器端进行操作,就不存在跨域问题了。
WebClient上传只包含键值对的文本信息示例代码:
代码如下:
string uriString = "http://localhost/login.aspx";
// 创建一个新的 WebClient 实例.
WebClient myWebClient = new WebClient();
string postData = "Username=admin&Password=admin";
// 注意这种拼字符串的ContentType
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
// 转化成二进制数组
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
// 上传数据,并获取返回的二进制数据.
byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
WebClient上传只包含文件的示例代码:
代码如下:
String uriString = "http://localhost/uploadFile.aspx";
// 创建一个新的 WebClient 实例.
WebClient myWebClient = new WebClient();
string fileName = @"C:/upload.txt";
// 直接上传,并获取返回的二进制数据.
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);
对于既包含文件又包含文本键值对信息的示例代码,需要构造表单提交的内容,对于学asp的同学来说,下面的表单提交内容一定不会陌生
代码如下:
-----------------------------7d429871607fe
Content-Disposition: form-data; name="file1"; filename="G:/homepage.txt"
Content-Type: text/plain
易贤网:
-----------------------------7d429871607fe
Content-Disposition: form-data; name="filename"
default filename
-----------------------------7d429871607fe--
所以只要拼一个这样的byte[] data数据Post过去,就可以达到同样的效果了。但是一定要注意,对于这种带有文件上传的,其ContentType是不一样的,例如上面的这种,其ContentType为"multipart/form-data; boundary=---------------------------7d429871607fe"。有了ContentType,我们就可以知道boundary(就是上面的"---------------------------7d429871607fe"),知道boundary了我们就可以构造出我们所需要的byte[] data了,最后,不要忘记,把我们构造的ContentType传到WebClient中(例如:webClient.Headers.Add("Content-Type", ContentType);)这样,就可以通过WebClient.UploadData 方法上载文件数据了。
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 // 加上结束边界
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 // 遍历复制
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 /// 获取普通表单区域二进制数组
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 // 头数据
063 string data = String.Format(textTemplate, fieldName, filename, contentType);
064 byte[] bytes = encoding.GetBytes(data);
065 // 尾数据
066 byte[] endBytes = encoding.GetBytes(end);
067 // 合成后的数组
068 byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];
069 bytes.CopyTo(fieldData, 0); // 头数据
070 fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据
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 // 生成需要上传的二进制数组
273 CreateBytes cb = new CreateBytes();
274 // 所有表单数据
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 // 合成所有表单并生成二进制数组
283 byte[] bytes = cb.JoinBytes(bytesArray);
284 // 返回的内容
285 byte[] responseBytes;
286 // 上传到指定Url
287 bool uploaded = cb.UploadData("http://localhost/UploadData/UploadAvatar.aspx", bytes, out responseBytes);
288 // 将返回的内容输出到文件
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技术专栏
2025国考·省考课程试听报名