1、HTTP上传文件及传递参数
#region 6.0 上传多个文件和参数
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, Dictionary<string,string> data, Encoding encoding)
{
//必须
string boundary = DateTime.Now.Ticks.ToString("X");
//必须的
//form 开始标志
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//form 结尾标志
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
//1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
using (Stream stream = request.GetRequestStream())
{
//传递参数模板 Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}
//1.1 key/value
string formdataTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}";
//传递参数
if (data != null)
{
foreach (string key in data.Keys)
{
//传递参数开始标识
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, data[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
//上传文件模板
//1.2 file
string headerTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
byte[] buffer = new byte[6*1024*1024];
for (int i = 0; i < files.Length; i++)
{
//上传文件标识
stream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
//将文件流读入到请求流中
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
int r = fileStream.Read(buffer,0,buffer.Length);
stream.Write(buffer, 0, r);
}
}
//form 结束标志
//1.3 form end
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string result = stream.ReadToEnd();
return result;
}
}
#endregion
2、测试:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text;
public partial class httpUpload_Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string url = "http://172.16.1.110:8888/httpUpload/Index.aspx";string pFilename1 = FileUpload1.PostedFile.FileName;
string pFilename2 = FileUpload2.PostedFile.FileName;
string pFilename3 = FileUpload3.PostedFile.FileName;
string[] files = new string[3] { pFilename1, pFilename2, pFilename3 };
//string[] files = new string[1] { pFilename1};
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("loginName", "测试");
data.Add("password", "123456");
string result = HttpUploadDemo.HttpUploadFile(url, files,data,Encoding.UTF8);
Response.Write(result);
}
}
3、HTML页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="httpUpload_Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /> <br /><br />
<asp:FileUpload ID="FileUpload2" runat="server" /> <br /><br />
<asp:FileUpload ID="FileUpload3" runat="server" /> <br /><br />
<asp:Button ID="Button1" runat="server"
Text="上传文件" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
4、服务器端
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
namespace WebThreadTest.httpUpload
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string password = this.Request["password"];
string loginName = this.Request["loginName"];
HttpFileCollection files = Request.Files;
if (files.Count<=0)
{
Response.Write("error");
return;
}
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files.Get(i);
string filename = file.FileName;
string extension = Path.GetExtension(filename);
string uploadFilename = DateTime.Now.ToFileTime() + extension;
string uploadDic = Server.MapPath(@"~/resource/httpUpload/");
if (!Directory.Exists(uploadDic))
{
Directory.CreateDirectory(uploadDic);
}
file.SaveAs(uploadDic + uploadFilename);
}
Response.Write("success");
}
}
}