不多说代码贴出来和大家分享一下:
1 XHTML代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadPic.aspx.cs" Inherits="UploadPic" %>
2 后台代码如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;
public partial class UploadPic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//判断是否选择文件
if (PicUpload.FileName=="")
{
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert('请选择图片')", true);
return;
}
else
{
//获取文件名
string filename = System.IO.Path.GetExtension(PicUpload.FileName);
//取的图片路径
string Pic_path = System.Web.HttpContext.Current.Request.MapPath("~/File/Pic/");
//获取文件路径
string Txt_path = System.Web.HttpContext.Current.Request.MapPath("~/File/Txt/");
if (filename==".jpg"||filename==".gif"||filename==".png")
{
//保存图片
PicUpload.SaveAs(Pic_path + PicUpload.FileName);
ScriptManager.RegisterStartupScript(this, GetType(), "msg","alert('图片上传成功!')", true);
}
else if (filename==".txt")
{
//保存文件
PicUpload.SaveAs(Txt_path + PicUpload.FileName);
ScriptManager.RegisterStartupScript(this, GetType(), "msg", "alert('文档上传成功!')", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "msg",string.Format("alert('上传失败!请上传.jpg .gif .png .txt 的文件')"), true);
}
}
}
}