关于FileUpload控件的二种用法,你都懂吗?
判断是上传的是否是.JPG图片
JS代码
<script type="text/javascript">
function chkPhoto(fnUpload)
{
var filename = fnUpload.value;
var mime = filename.toLowerCase().substr(filename.lastIndexOf("."));
if (mime!=".jpg")
{
alert("请选择JPG格式的图片!");
fnUpload.outerHTML=fnUpload.outerHTML;
}
}
</script>
标签代码 注意 onchage事件
<asp:FileUpload ID="fnPhoto" runat="Server" onchage="chkPhoto(this)" />
为Image控件设定默认图片 和出错时的图片
<asp:Image ID="Image1" runat="server" ImageUrl="~/image/HR201234170434507500.jpg" Width="180px" Height="200px" onerror="this.src='/webJPG/image/HR201234170434507500.jpg'"/>
关于上传按钮代码
protected void Button1_Click(object sender, EventArgs e)
{
string ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
string str = "HR"+DateTime.Now.ToString("yyyymmddhhmmssffff");
Response.Write(str);
string path = "~/image/" + str + ".jpg";
string sql = string.Format("insert into tb_image(image) values('{0}')", path);
SqlConnection scon = new SqlConnection(ConStr);
scon.Open();
SqlCommand cmd = new SqlCommand(sql, scon);
try
{
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), null, "alert('添加成功!')", true);
if (FileUpload1.FileName != "")
{
FileUpload1.SaveAs(Server.MapPath(path));
this.Image1.ImageUrl = path;
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), null, "alert('添加失败!')", true);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
先添加using System.IO;命名空间
protected void Button1_Click(object sender, EventArgs e) //方法一
{
//上传文件到load下的upload文件夹
FileUpload1.SaveAs(Server.MapPath("load/upload"+"\\"+Path.GetFileName(FileUpload1.PostedFile.FileName)));
//获取上传文件的名称
Response.Write(FileUpload1.PostedFile.FileName+"<br>");
//获取上传文件的类型
Response.Write(FileUpload1.PostedFile.ContentType+"<br>");
//获取上传文件的大小
Response.Write(FileUpload1.PostedFile.ContentLength);
string strpath=FileUpload1.PostedFile.FileName;
//获取文件的扩展名
Response.Write(strpath.Substring(strpath.LastIndexOf(".") + 1));
}
protected void Button2_Click(object sender, EventArgs e) //方法二
{
HttpPostedFile pf = this.FileUpload1.PostedFile;
//获取上传文件的完整路径
Response.Write("上传文件路径为::"+pf.FileName+"<br>");
//获取上传文件的类型
Response.Write("上传文件的类型为:" + Path.GetExtension(pf.FileName)+"<br>");
//获取上传文件的大小
Response.Write(pf.ContentLength.ToString());
//上传文件到load文件夹下的upload文件夹
pf.SaveAs(Server.MapPath("load/upload" + "\\" + Path.GetFileName(pf.FileName)));
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!