前台:
HTML的代码:(关键是要在form里设置enctype="multipart/form-data",这样才能在提交表单时,将文件以二进制流的形式传输到服务器)
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title>无标题页</title>
</head>
<body>
<form
id="Form1" action="/json/ajax/WinLog.aspx" method="post"
enctype="multipart/form-data">
<div style="text-align:
center">
填写用户信息
<hr style="size: 50%" />
</div>
<div style="text-align: left">
用户名:<input name="user_name"
type="text" /><br />
密码:
<input name="Password1"
type="password" /><br />
确认密码:<input name="Password2"
type="password" /><br />
性别:<input name="女" type="radio"
value="女" />女<input id="Radio1" type="radio" value="男"
name="sex"
/>男<br />
上传照片:<input id="File1" type="file" name="picture"
/><br />
<br />
<input type="submit"
value="提交" />
<input type="reset" value="重置"
/></div>
</form>
</body>
</html>
后台:
namespace benz_CSI.json.ajax
{
public partial class WinLog :
System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
Response.Write("利用
Response对象获取客户端数据");
Response.Write("<hr/>");
string[]
names = Request.Form.AllKeys;//定义name保存表单中的所有键即元素名称
for (int i = 0; i <
names.Length; i++)
{
string[] values =
Request.Form.GetValues(i);//定义values保存表单中所有键的键值
for (int j = 0; j <
values.Length; j++)
Response.Write(names[i] + "=" +
values[j] + "<br/>");
}
Response.Write("<hr/>");
Response.Write(Request.Form["picture"]);
SaveFile(Request.Form["picture"]);
}
public bool SaveFile(string filePath)
{
if (Request.Files.Count >= 1)
{
HttpPostedFile postedFile = Request.Files[0];
string
fileName, fileExtension;
fileName =
System.IO.Path.GetFileName(postedFile.FileName); //文件名称
if (fileName !=
"")
{
fileExtension =
System.IO.Path.GetExtension(fileName); //上传文件的扩展名
string new_filename =
DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension; //给文件重新命名
string
FileTemp = Page.MapPath("/json/ajax/upload/");
postedFile.SaveAs(FileTemp + new_filename);
Response.Write("文件 类 型:" + postedFile.ContentType.ToString() +
"<br/>");
Response.Write("文件新名称:" + new_filename +
"<br/>");
Response.Write("文件原名称:" + fileName +
"<br/>");
Response.Write("文件扩展名:" + fileExtension +
"<br/>");
Response.Write("文件原路径:" +
postedFile.FileName + "<br/>");
Response.Write("文件新路径:" + FileTemp + new_filename + "<br/>");
}
else
{
Response.Write("false");
}
}
return true;
}
}
}