柔城

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 2017-01-21 12:42  柔城  阅读(5154)  评论(1编辑  收藏  举报

导航