表单中enctype="multipart/form-data"的意思,是设置表单的MIME 编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart /form-data,才能完整的传递文件数据,进行下面的操作.
enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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 method="post" enctype="multipart/form-data" action="Default2.aspx">
<div>
<input type="file" name="img" /><input type="submit" value="提交" /></div>
</form>
</body>
</html>
using System;
using System.Web;
using System.IO;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//图片保存
HttpFileCollection files = Request.Files;
string fileDestination = string.Empty;
if (files.Count > 0)
{
HttpPostedFile postedFile = Request.Files[0];
string fileName = Path.GetFileName(postedFile.FileName);
if (fileName != "")
{
SaveFile(postedFile, "IMAGE");
}
}
}
public string SaveFile(HttpPostedFile postedFile, string postType)
{
string UploadFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
string extension = Path.GetFileName(postedFile.FileName);
string strFileName = HttpContext.Current.Request.ApplicationPath + "//UpLoadFile//" + postType + "//" + System.DateTime.Today.Year.ToString() + "//" + System.DateTime.Today.Month.ToString() + "//";
string root = System.Web.HttpContext.Current.Server.MapPath(strFileName);
string destination = System.Web.HttpContext.Current.Server.MapPath(strFileName) + UploadFileName + extension;
string path = "/UpLoadFile/" + postType + "/" + System.DateTime.Today.Year.ToString() + "/" + System.DateTime.Today.Month.ToString() + "/" + UploadFileName + extension;
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
postedFile.SaveAs(destination);
return path;
}
}