在目前做的移动项目开发中,我负责了一个文件上传控件的开发。(效果图如上)在开发的过程中遇到了一些问题,但最后通过不段的查找和测试,终于把问题解决了。下面我把解决问题的思想记录下来,愿意和朋友们分享。当然也希望朋友们能提出其他的解决方案。共同交流。
说起上传就不得不谈到文件上传控件:

然而这个上传控件是一个文本框和一个按钮,这个按钮的样式和目前所做的项目中的风格基本是不一致的。于是想打算用一个文本框和一个图片按钮来模仿上传功能。
在上网查找相关资料,得到下面一些信息:
我们知道,大部分控件都有一个单击(Click)事件句柄,上传框在点击”浏览”文件对话框,如果我们自己模拟一个上传框,和一个按钮,在单击自定义按钮时候同事触发上传框的Click事件让它弹出文件对话框:





然而当该代码放在表单中时候,点击提交表单时候,真正的上传框的内容被清空了。意思就是说,这样模拟出来的上传框没有任何意义的。因为没有办法上传文件。之所以是这样的结果,估计是因为微软处于安全方面的考虑。只有当鼠标真正上传在上传控件的按钮上浏览到的文件才可以看到(否则你进入我的页面,我就可以随心所欲的得到你的私密文件).
看来用这种方法是行不通的。于是在网上又找了一种思路:当鼠标移动到上传图片的按钮上时候,让真正的文件上传控件移动到鼠标所在的按钮位置上,那样的话当点击按钮时候,实际上点击的是真正的文件上传控件(设置透明度为0),这样不就解决问题了吗?
参考下面的代码:
















上面的代码我把它放在新建立的一个aspx页面上做了一个测试,果然能够在服务器端能够访问到客户端上传的文件名。
上面的测试成功了。然而我把上面的代码放到实际的页面上时候,确另我大吃一惊。当鼠标移动到按钮上的时候,那个真正的文件上传控件没有移动到按钮上来。当点击按钮时候就没有反应。后来才发现真正的项目页面中运用了iframe框架,于是我就绝对那个控制位置的那段脚本在框架页面尚好像不是很符合。于是我修改那段脚本。但最后的效果都不是很另人满意。这个问题花了我近1天时间,真是太郁闷了。
最后,听了同事们的建议,终于找到了一个方法来实现:
让真正的文件上传控件和模拟的上传按钮分别放到一个层里面去。然后让这2个层重叠。设置z-index属性,让真正的文件上传控件所在的层在外面,并设置为透明。这样当点击按钮时候实际尚就点击文件上传控件了。根本就不需要那脚本来控制控件的位置。
的确是一个好方法。我按照这个思想终于实现了。下面是参考代码:

























在服务器端访问上传的文件名:this.fileAttachment.PostedFile.FileName果然能正常访问,而且我把这个控件放到包含框架的页面上也能准确的定位。简直太妙了。
下面是显示的效果:是不是比默认的要好看多了。和项目的风格和统一起来了.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验