没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
全文可编辑 word 文档 页眉与背景水印可删除
1
Asp.Net 模拟表单提交数据和上传文件的实
现代码
如果你需要跨域上传内容到另外一个域名并且需要获
取返回值,使用 Asp.Net 的作为代理是最好的办法,要是客
户端直接提交到 iframe 中,由于跨域是无法用 javascript
获取到 iframe 中返回的内容的。此时需要在自己的网站做
一个动态页作为代理,将表单提交到动态页,动态页负责将
表单的内容使用 WebClient 或 HttpWebRequest 将表单数据
再上传到远程服务器,由于在服务器端进行操作,就不存在
跨域问题了。
WebClient 上传只包含键值对的文本信息示例代码:
WebClient 上传只包含文件的示例代码:
对于既包含文件又包含文本键值对信息的示例代码,
需要构造表单提交的内容,对于学 asp 的同学来说,下面的
表单提交内容一定不会陌生
所以只要拼一个这样的 byte[] data 数据 Post 过去,
就可以达到同样的效果了。但是一定要注意,对于这种带有
文件上传的,其 ContentType 是不一样的,例如上面的这种,
其 ContentType 为 "multipart/form-data;
全文可编辑 word 文档 页眉与背景水印可删除
2
boundary=---------------------------7d429871607fe"。
有了 ContentType,我们就可以知道 boundary(就是上面的
"---------------------------7d429871607fe") , 知 道
boundary 了我们就可以构造出我们所需要的 byte[] data 了,
最后,不要忘记,把我们构造的 ContentType 传到 WebClient
中 ( 例 如 :webClient.Headers.Add("Content-Type",
ContentType);)这样,就可以通过 WebClient.UploadData
方法上载文件数据了。
using System;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
namespace UploadData.Common
{
public class CreateBytes
{
Encoding encoding = Encoding.UTF8;
public byte[] JoinBytes(ArrayList
byteArrays)
全文可编辑 word 文档 页眉与背景水印可删除
3
{
int length = 0;
int readLength = 0;
// 加上结束边界
string endBoundary = Boundary + "-- ";
byte[] endBoundaryBytes =
encoding.GetBytes(endBoundary);
byteArrays.Add(endBoundaryBytes);
foreach (byte[] b in byteArrays)
{
length += b.Length;
}
byte[] bytes = new byte[length];
// 遍历复制
foreach (byte[] b in byteArrays)
{
b.CopyTo(bytes, readLength);
readLength += b.Length;
}
return bytes;
}
public bool UploadData(string uploadUrl,
全文可编辑 word 文档 页眉与背景水印可删除
4
byte[] bytes, out byte[] responseBytes)
{
WebClient webClient = new
WebClient();
webClient.Headers.Add("Content-Type
", ContentType);
try
{
responseBytes =
webClient.UploadData(uploadUrl, bytes);
return true;
}
catch (WebException ex)
{
Stream resp =
ex.Response.GetResponseStream();
responseBytes = new
byte[ex.Response.ContentLength];
resp.Read(responseBytes, 0,
responseBytes.Length);
}
return false;
全文可编辑 word 文档 页眉与背景水印可删除
5
}
/// 获取普通表单区域二进制数组
public byte[] CreateFieldData(string
fieldName, string fieldValue)
{
string textTemplate = Boundary + "
Content-Disposition: form-data; name="{0}" {1} ";
string text =
String.Format(textTemplate, fieldName, fieldValue);
byte[] bytes =
encoding.GetBytes(text);
return bytes;
}
public byte[] CreateFieldData(string
fieldName, string filename, string contentType, byte[]
fileBytes)
{
string end = " ";
string textTemplate = Boundary + "
Content-Disposition: form-data; name="{0}";
filename="{1}" Content-Type: {2} ";
// 头数据
剩余21页未读,继续阅读
资源评论
mmoo_python
- 粉丝: 0
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功