Http请求中的multipart/form-data,它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开。既可以上传键值对,也可以上传文件。当上传的字段是文件时,会有Content-Type来表名文件类型;content-disposition用来说明字段的一些信息;由于有boundary隔离,所以multipart/form-data既可以上传文件,也可以上传键值对,它采用了键值对的方式,所以可以上传多个文件。
C#使用HttpRequest进行Post表单传送的时候爆 (500) Internal Server Error.
原因为ContentType设置为multipart/form-data;需要改为
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
request.ContentType = "multipart/form-data; boundary="+boundary;
附C# multipart/form-data类型上传文件、表单代码:
//上传文件所需要的参数
public class UpLoadFile
{
//上传名字
public string Name { get; set; }
//文件名
public string FileName { get; set; }
//文件全名 包含路径
public string FileFullName { get; set; }
//文件路径
public string FilePath { get; set; }
//文件Post上传路径
public string FileContentType { get; set; }
}
/// <summary>
/// 发起httpPost 请求,可以上传文件
/// </summary>
/// <param name="url">请求的地址</param>
/// <param name="upLoadFiles">上传的文件参数</param>
/// <param name="formdatastrdict">表单数据</param>
/// <param name="headersdict">头文件</param>
/// <param name="endoding">编码类型</param>
/// <returns></returns>
public static string PostResponse(string url, List<UpLoadFile> upLoadFiles, Dictionary<string, string> formdatastrdict, Dictionary<string, string> headersdict, Encoding endoding)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//添加头文件
if (headersdict != null)
{
foreach (var key in headersdict.Keys)
{
request.Headers.Add(key, headersdict[key]);
}
}
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
//request.Credentials = CredentialCache.DefaultCredentials;
request.Expect = "";
MemoryStream stream = new MemoryStream();
byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "
");
byte[] enterER = Encoding.ASCII.GetBytes("
");
//提交文本字段
if (formdatastrdict != null)
{
string format = "--" + boundary + "
Content-Disposition:form-data;name="{0}"
{1}
"; //自带项目分隔符
foreach (string key in formdatastrdict.Keys)
{
string s = string.Format(format, key, formdatastrdict[key]);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
}
}
//提交文件 应放在文本后面
if (upLoadFiles != null)
{
string fformat = "Content-Disposition:form-data; name="{0}";filename="{1}"
Content-Type:{2}
";
foreach (var file in upLoadFiles)
{
stream.Write(line, 0, line.Length); //项目分隔符
//application/octet-stream
string s = string.Format(fformat, file.Name, file.FileName, file.FileContentType);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
int bytesRead;
byte[] buffer = new byte[1024];
FileStream fileStream = new FileStream(file.FileFullName, FileMode.Open, FileAccess.Read);
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
//将文件流写入FormData项中
stream.Write(buffer, 0, bytesRead);
}
//添加
stream.Write(enterER, 0, enterER.Length);
}
}
//项目最后的分隔符字符串需要带上--
byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--
");
stream.Write(foot_data, 0, foot_data.Length);
request.ContentLength = stream.Length;
//写入请求数据
Stream requestStream = request.GetRequestStream();
stream.Position = 0L;
stream.CopyTo(requestStream);
stream.Close();
requestStream.Close();
try
{
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
try
{
using (var responseStream = response.GetResponseStream())
using (var mstream = new MemoryStream())
{
responseStream.CopyTo(mstream);
string message = endoding.GetString(mstream.ToArray());
return message;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
}
catch (WebException ex)
{
//response = (HttpWebResponse)ex.Response;
//if (response.StatusCode == HttpStatusCode.BadRequest)
//{
// using (Stream data = response.GetResponseStream())
// {
// using (StreamReader reader = new StreamReader(data))
// {
// string text = reader.ReadToEnd();
// Console.WriteLine(text);
// }
// }
//}
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}
}