柔城

SOSOFT articles

asp.net上传图片到服务器

ASP.NET的FileUpload控件可用于上传文件到服务器。HoverTreeTop新增了一个“阅图”功能,图片就是用FileUpload上传的。阅图功能查看:http://hovertree.com/top/htimg/

这里要说明的是上传图片限定文件名和文件大小等代码。

文件上传功能使用用户控件实现,在HoverTreePanel项目中的HTPanel\HControl\UCPictureAdd.ascx 控件,
HoverTreeTop上传的图片文件暂时限定为jpg、png和gif。代码为:

<asp:FileUpload runat="server" ID="fileUpload_hovertree" ClientIDMode="Static" accept="image/png,image/jpeg,image/gif" />

c#代码:

HtPictureInfo h_info = new HtPictureInfo();
            h_info.HtSuffix = HoverTreeImageTool.GetGpjImageFileExtension(fileUpload_hovertree.PostedFile.ContentType);
            if (h_info.HtSuffix == "")
            {
                literal_tips.Text = "请选择jpg,png或者gif图片文件";
                return;
            }

其中GetGpjImageFileExtension方法在HoverTreeFrame项目中,代码:

复制代码
namespace HoverTree.HoverTreeFrame.HtImage
{
    public class HoverTreeImageTool
    {
        /// <summary>
        /// 根据图片文件的mime内容类型获取文件的后缀名,如果不是gif,png或者jpg图片文件则返回空字符串
        /// http://hovertree.com/h/bjag/viv8qlpx.htm
        /// http://hovertree.com/texiao/h/contenttype/
        /// </summary>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string GetGpjImageFileExtension(string contentType)
        {
            switch (contentType)
            {
                case "image/jpeg":
                    return "jpg";
                case "image/pjpeg":
                    return "jpg";
                case "image/gif":
                    return "gif";
                case "image/png":
                    return "png";
                case "image/x-png":
                    return "png";
                default:
                    return string.Empty;
            }
        }
    }
}
复制代码

也就是使用ContentType获取并验证后缀名。参考:http://hovertree.com/texiao/h/contenttype/

还有一个就是限定上传文件的大小,暂时限定为1M,代码如下:

if (fileUpload_hovertree.PostedFile.ContentLength > 1048576)
            {
                literal_tips.Text = "选择的文件太大。";
                return;
            }

1048576字节也就是1M。
上传使用SaveAs方法就可以:
fileUpload_hovertree.SaveAs(h_fullName);
其中h_fullName为完整文件名字符串。

HoverTreeTop项目:
http://hovertree.com/top/
源码下载:
http://hovertree.com/h/bjaf/hv6cqe5n.htm

转自:

http://hovertree.com/h/bjag/o5rdqyrb.htm

推荐:

http://www.cnblogs.com/sosoft/p/kaifajishu.html

posted on   柔城  阅读(5164)  评论(1编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2014-01-21 前端代码标准最佳实践:CSS
2014-01-21 开始ASP.NET MVC5之旅

导航

统计

点击右上角即可分享
微信分享提示