惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
W
WeLiveSecurity
Cyberwarzone
Cyberwarzone
H
Help Net Security
Spread Privacy
Spread Privacy
Jina AI
Jina AI
G
GRAHAM CLULEY
Project Zero
Project Zero
aimingoo的专栏
aimingoo的专栏
P
Palo Alto Networks Blog
云风的 BLOG
云风的 BLOG
B
Blog RSS Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
A
Arctic Wolf
L
LangChain Blog
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
人人都是产品经理
人人都是产品经理
罗磊的独立博客
量子位
Microsoft Security Blog
Microsoft Security Blog
The Register - Security
The Register - Security
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
小众软件
小众软件
Vercel News
Vercel News
V
Visual Studio Blog
IT之家
IT之家
C
Cisco Blogs
博客园 - 聂微东
Cisco Talos Blog
Cisco Talos Blog
Help Net Security
Help Net Security
S
Schneier on Security
PCI Perspectives
PCI Perspectives
C
Check Point Blog
V
Vulnerabilities – Threatpost
J
Java Code Geeks
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
GbyAI
GbyAI
N
News and Events Feed by Topic
AWS News Blog
AWS News Blog
L
LINUX DO - 热门话题
SecWiki News
SecWiki News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future

博客园 - 站在天空下的猪

SqlBulkCopy批量转移数据备注 根据文本框联动下拉框(jquery 插件) - 站在天空下的猪 - 博客园 关于用FOMR提交编码的问题 jquery 图片预览插件 - 站在天空下的猪 - 博客园 自己写的一个jquery模板引擎(json比较好用) Document 对象的常用方法 今天发现梅花雨日历控件蛮好用的哟,腾讯都在用 身份证对应县及县的行政区划代码 【SQLSERVER】存储过程基础 终于解决了一个AjaxPro无刷新的问题了,可以引用在短信方面滴asp.net 2.0 昨天很失败 C# 判断是否为数字 DataBinder.Eval总结 asp.net 2.0中实现防盗链 如何把HTML语句直接保存到数据库 如何取得IP/用户名等信息 “ConnectionString 属性尚未初始化”的另类解决办法 asp.net常用函数表 C#中计算两个时间的差
一个简单的FileUpload处理逻辑
站在天空下的猪 · 2007-05-21 · via 博客园 - 站在天空下的猪

 配合ASP.NET 2.0提供了FileUpload控件,很容易就可以完成文件上传功能。做了一个简单的上传逻辑,实现了:检查了文件是否存在、自动生成文件名、自动建立上传文件夹、对文件类型作校验等功能。

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Web;
 5using System.IO;
 6using System.Web.Configuration;
 7using System.Configuration;
 8using System.Web.Security;
 9using System.Web.UI.WebControls;
10namespace QmxMovieBLL
11
12{
13    public class UploadFileBLL
14    {
15        string filePath = ConfigurationManager.AppSettings["UploadImages"].ToString();
16        private string GenerateRefUploadFileName(string ext)
17        
18            string fileName;//初始文件名
19            string hashedFileName;//加密过的文件名
20            string refUploadDest;//最终上传地址(映射过的)
21            int count = 0;
22            do
23            {
24                if(count++>=32767throw new Exception("生成文件名失败,请重新进行此操作!");//防止死循环
25                fileName = DateTime.Now.ToString() + DateTime.Now.Millisecond.ToString();
26                hashedFileName = FormsAuthentication.HashPasswordForStoringInConfigFile(fileName, "MD5");
27                refUploadDest =Path.Combine(filePath, hashedFileName);
28            }
 while (File.Exists(HttpContext.Current.Server.MapPath(refUploadDest)));
29            return refUploadDest+ext;
30        }

31
32        private bool CanUpload(string ext)
33        
34            //TODO:是否合法的扩展名
35            //允许上传的图片格式为jpg/jpeg、png和gif类型
36            if (ext.ToLower() == ".jpg" || ext.ToLower() == ".jpeg" || ext.ToLower() == ".png"
37                || ext.ToLower() == ".gif")
38            {
39                return true;
40            }

41            return false;
42        }

43
44        private bool FileTypeAllowed(FileUpload fu)
45        {
46            //是否合法的文件类型,通过FileUpload的ContentType属性来确定类型
47            string fileType = fu.PostedFile.ContentType.ToString().ToLower();
48            if (fileType == "image/pjpeg" || fileType == "image/x-png" || fileType == "image/gif"return true;
49            return false;
50            
51        }

52
53        public string UploadFile(FileUpload fu)
54        {
55            if (fu.HasFile)
56            {
57                string fileName = fu.FileName;
58                //Response.Write(fu.PostedFile.ContentType.ToString().ToLower());
59                string ext = Path.GetExtension(fileName).ToLower();
60                //首先,验证是否可以上传该文件
61                if (!CanUpload(ext)||!(FileTypeAllowed(fu)))
62                {
63                    throw new Exception("不是允许的上传文件类型!");
64                }

65
66                if (!Directory.Exists(HttpContext.Current.Server.MapPath(filePath)))
67                {
68                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(filePath));
69                }

70
71                string refDest;
72                try
73                {
74                    refDest = GenerateRefUploadFileName(ext);
75                }

76                catch (Exception ex)
77                {
78                    throw ex;
79                }

80                string realDest = HttpContext.Current.Server.MapPath(refDest);
81                try
82                {
83                    fu.SaveAs(realDest);
84                }

85                catch (Exception)
86                {
87                    throw new Exception("文件保存出错。请检查上传文件夹是否存在。");
88                }

89                return refDest;
90            }

91            else
92            {
93                throw new Exception("请选择要上传的文件。");
94            }

95        }

96
97    }

98}

要实现这个可以用到FileUpload的ContentLength属性,此属性返回要上传文件的字节数。例如,可以写一个方法,设置测试大小限制为10字节:

        /// <summary>
        
/// 检查文件的大小是否合法
        
/// </summary>
        
/// <param name="fu"></param>
        
/// <returns></returns>

        private bool IsUploadSizeFit(FileUpload fu)
        
{
            
const int maxFileSize = 10;
            
if (fu.PostedFile.ContentLength > maxFileSize) return false;
            
return true;
        }

在上文第65行位置插入如下代码:

//如果文件上传大小超过限制,则不允许上传
if (!IsUploadSizeFit(fu))
{
    
throw new Exception("文件大小超过允许范围!");
}

完成的功能如下:


99