[代码分享]上传文件到服务器(普通表单数据和文件)
这是通过嗅探工具 得到表单提单上传的数据。。
POST xxxxxxx HTTP/1.1
Accept: image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Referer: xxxxxxx
Accept-Language: zh-CN
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)
Content-Type: multipart/form-data; boundary=---------------------------7dbdd139a1514
Accept-Encoding: gzip, deflate
Host: xxxxxxx
Content-Length: xxxxxxx
Connection: Keep-Alive
Pragma: no-cache
Cookie: xxxxxxx
-----------------------------7dbdd139a1514
Content-Disposition: form-data; name="Employee.EmployeeId"
1
-----------------------------7dbdd139a1514
Content-Disposition: form-data; name="filePhoto"; filename="P1100353.JPG"
Content-Type: image/pjpeg
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
其中,Content-Type的内容为: multipart/form-data;我们在做上传文件时,都要设置表单的 enctype="multipart/form-data"的,设置这个属性后,上传的数据就会变成
-----------------------------7dbdd139a1514
Content-Disposition: form-data; name="Employee.EmployeeId"
1
这样的。
下面是代码.
[code=C]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.Net.Mime;
using System.Globalization;
using System.IO;
namespace Helper
{
/// <summary>
/// 上传
/// </summary>
public class UploadHelper
{
// 边界数据
/// <summary>
/// 边界数据(boundary = "---------------------------7db38610205dc")
/// </summary>
public string BoundaryData { get; set; }
//数据编码
/// <summary>
/// 数据编码,默认为UTF8
/// </summary>
public Encoding Encoding { get; set; }
//尾部数据
/// <summary>
/// 尾部数据
/// </summary>
private string EndData
{
get
{
return Environment.NewLine + "--" + this.BoundaryData + "--" + Environment.NewLine;
}
}
/// <summary>
/// ctor
/// </summary>
public UploadHelper()
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.CurrentInfo);
this.BoundaryData = boundary;
this.Encoding = Encoding.UTF8;
}
/// <summary>
/// ctor
/// </summary>
public UploadHelper(Encoding encoding)