![]() |
asp.net上传文件:(该控件名为tx)
string path="upload/"+txtyhm.Text.Trim()+"/";
if (!(Directory.Exists(Server.MapPath(path))))//判断这个文件夹是否存在
{
//Label1 = Server.MapPath("upload/").ToString() + txtyhm.Text;
Directory.CreateDirectory(Server.MapPath(path));//建立新文件夹
}
HttpPostedFile hpf = tx.PostedFile;//这个类能测试文件的大小
string file = "";
string exfile = "";
file = tx.FileName;
int pos = file.LastIndexOf(".");//查找文件名最后的点的位置
exfile = file.Substring(pos + 1);
if (!(exfile == "png" || exfile == "jpg" || exfile == "ico"))
{
Response.Write("<script>alert('必须选择图片')</script>");
return;
}
if (hpf.ContentLength(Server.MapPath(path))>1024*1024)
{
Response.Write("<script>alert('文件太大')</script>");
}
if (tx.HasFile)
{
string filePath = Server.MapPath(path);
string fileName = tx.PostedFile.FileName;
string newfile = fileName;
if (hpf.ContentLength > 1024 * 1024)
{
Response.Write("<script>alert('上传文件大小不能超过1M');</script>");
return;
}
if (File.Exists(Server.MapPath(path)))
{ newfile = DateTime.Now.ToString("yyyymmhhmmss") + fileName; }
newfile = DateTime.Now.ToString("yymmdd") + "." + exfile;
tx.SaveAs(Server.MapPath(path) + newfile);
//Label1.Text = Server.MapPath(path) + newfile;
//Label1.Text = hpf.ContentLength(Server.MapPath(path) + newfile);
//if (hpf.ContentLength(Server.MapPath(path)+newfile)>10*1024*1024)
//{/}
//Image1.ImageUrl = path+"/"+ newfile;
//Response.Write("<p >上传成功!</p>");
Label2.Text = "上传文件大小为:"+hpf.ContentLength.ToString();
Response.Write("<script>alert('上传成功!')</script>");
ViewState["photo"] = path+"upload/" + file;
//Label1.Text = Server.MachineName+Server.ScriptTimeout+Server.MapPath("login.aspx");
}
else
{
Response.Write("<p >请选择要上传的文件!</p>");
}
if (!(Directory.Exists(Server.MapPath(path))))
{
//Directory.Delete(Server.MapPath(path));
Directory.CreateDirectory(Server.MapPath(path));
}
if (Directory.Exists(Server.MapPath(path)))
{
Directory.Delete(Server.MapPath(path));
//Directory.CreateDirectory(Server.MapPath(path));
}
//Label1.Text = Server.MachineName;
//Directory.Delete(Server.MapPath(path));
//string path = Server.MapPath("Image");
path = Server.MapPath(path);
Label1.Text = path;
//获取文件夹中所有图片
//if (Directory.GetFileSystemEntries(path).Length > 0)
//{
// //遍历文件夹中所有文件
// foreach (string file in Directory.GetFiles(path))
// {
// //文件己存在
// if (File.Exists(file))
// {
// FileInfo fi = new FileInfo(file);
// //判断当前文件属性是否是只读
// if (fi.Attributes.ToString().IndexOf("ReadyOnly") >= 0)
// {
// fi.Attributes = FileAttributes.Normal;
// }
// //删除文件
// File.Delete(file);// }
// }
// //删除文件夹
// Directory.Delete(path);//}