您的位置:首页 > 其它

form表单提交上传附件

2014-11-06 16:58 225 查看
<form method="post" action="/ aa/post" enctype="multipart/form-data">

name:<input type="text" id="name" name="name" style=" width:500px; margin-left:9px" />

上传附件:<input type="file" id="files" name="files" runat="server"style=" width:500px; margin-left:9px" />

<button type="submit" >提交</button>

</form>

protected string AllowExt = "bmp|doc|docx|gif|jpeg|jpg|pdf|png|ppt|pptx|txt|xls|xlsx";//支持的文件格式

int FileMaxSize = 10240;//文件大小,单位为K

public ActionResult post( MODELNAME model)

{

System.Web.HttpContext.Current.Response.ContentType = "text/plain";

string ParentID = System.Web.HttpContext.Current.Request.Params["id"];

HttpPostedFile fileUpload = System.Web.HttpContext.Current.Request.Files[0];

if (fileUpload != null)

{

string UploadDir = "~/upload/";//图片保存的文件夹

//图片保存的文件夹路径

string path = System.Web.HttpContext.Current.Server.MapPath(UploadDir);

//每天上传的图片一个文件夹

string folder = DateTime.Now.ToString("yyyyMM");

//如果文件夹不存在,则创建

if (!Directory.Exists(path + folder))

{

Directory.CreateDirectory(path + folder);

}

//上传图片的扩展名

string fileExtension = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf('.'));

//判断文件格式

if (!CheckValidExt(fileExtension))

{

System.Web.HttpContext.Current.Response.Write("错误提示:文件格式不正确!" + fileExtension);

}

//判断文件大小

if (fileUpload.ContentLength > FileMaxSize * 1024)

{

System.Web.HttpContext.Current.Response.Write("错误提示:上传的文件(" + fileUpload.FileName + ")超过最大限制:" + FileMaxSize + "KB");

}

//保存图片的文件名

//string saveName = Guid.NewGuid().ToString() + fileExtension;

//使用时间+随机数重命名文件

string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff");//取得时间字符串

Random ran = new Random();

string strRan = Convert.ToString(ran.Next(100, 999));//生成三位随机数

string saveName = strDateTime + strRan + fileExtension;

SYS_FILE file = new SYS_FILE();

file.SID = CommonBLL.GetMaxID("SYS_FILE");

file.CREATE_DATE = DateTime.Now;

file.CREATEUSER_NAME = user.LOGINNAME;

file.CREATEUSER_SID = user.SID;

file.EXTNAME = fileExtension;

file.FILELENGTH = fileUpload.ContentLength;

file.FILENAME = fileUpload.FileName;

file.FILEPATH = UploadDir + folder + "/" + saveName;

fileUpload.SaveAs(path + folder + "/" + saveName);

SYS_FILEBLL.Add(file);

}

MODELNAMEBLL.Add(model);

return View("viewname", model);

}

注意:Current.Request.Files 为空 原因
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: