asp.net 用FileUpload上传文件到文件夹

using System;
using System.Data;
using System.Configuration;
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;
public class Upfield : System.Web.UI.Page
{
public Upfield()
{
}
public void Upfile(FileUpload Fiup2)
{
string savePath = (System.Web.HttpContext.Current.Server.MapPath("..\\..\\FileSave" + "\\" + Session["id"]));
string[] allowExtensions = { ".doc",".docx",".pptx",".ppt",".xls",".xlsx",".jpg",".jpeg",".gif",".png","pdf",".rar",".zip",".7z",".txt" };
string fileExtensi = System.IO.Path.GetExtension(Fiup2.FileName).ToLower();
int a = 0;
for (int i = 0; i < allowExtensions.Length; i++)
{
if (fileExtensi == allowExtensions[i])
a=1;
}
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
else
{
if (Fiup2.HasFile)
{
if (a != 0)
{
if (Fiup2.PostedFile.ContentLength < 10485760)
{
try
{
string fileName = Fiup2.FileName;
HttpPostedFile postFile = Fiup2.PostedFile;
string dfileName = Path.GetFileName(Fiup2.FileName).Replace(Path.GetExtension(Fiup2.FileName), " ").Replace("+", " ");
string lfileType = fileName.Substring(fileName.LastIndexOf(".") + 1);
string time1 = DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace("-", "").Replace(" ", "");
String lfileName = dfileName + time1 + "." + lfileType;
Fiup2.SaveAs(System.Web.HttpContext.Current.Server.MapPath("..\\..\\FileSave" + "\\" + Session["id"] + "\\" + lfileName));
String fileType = Fiup2.PostedFile.ContentType;
int fileSize = Fiup2.PostedFile.ContentLength;
String fileMapPath = "..\\..\\FileSave" + "\\" + Session["id"] + "\\" + Fiup2.FileName; //上传文件夹的路径,自己修改
String fileTime = DateTime.Now.ToString();

/*Static.setSuZu(fileName, lfileName, fileType, fileSize, fileMapPath, Static.i); //写入预存数组
Static.i++; //i++;*/ 为多文件上传做的标记,可不用
}
catch (Exception ex)
{
throw new Exception("上传发生错误!");
}
}
else
{
throw new Exception("请上传小于10M的文件");
}
}
else
{
throw new Exception("请上传合适的文件类型");
}
}
else
{
throw new Exception("请选择要上传的文件!");
}
}
}

}


这是文件上传封装类,需要时,自己调用,调用方法如下:

protected void BtFadd_Click(object sender, EventArgs e) //上传
{
try
{
Upfield up = new Upfield();
up.Upfile(Fiup2);
}
catch(Exception ex)
{
Response.Write("<script language='javascript'>alert('"+ex.Message+"')</script>");
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值