002 |
using System.Collections.Generic; |
010 |
/// 單文件上傳類 (暫時(shí)不支持多文件上傳) |
011 |
/// yangyunzhou@foxmail.com |
013 |
public class UploadFile |
016 |
/// 上傳文件信息 (動(dòng)態(tài)數(shù)組) |
018 |
public Dictionary< string , dynamic> FileInfo = new Dictionary< string , dynamic>(); |
023 |
public int FileSize = 10240; |
028 |
public string FilePath = "/Upload" ; |
031 |
/// 允許上傳的文件類型, 逗號(hào)分割,必須全部小寫! |
033 |
/// 格式: ".gif,.exe" 或更多 |
035 |
public string FileType = ".jpg,.gif,.png,.bmp" ; |
045 |
public string Message; |
050 |
/// <param name="FormField">表單文件域名稱</param> |
051 |
public void Save( string FormField) |
053 |
var Response = HttpContext.Current.Response; |
054 |
var Request = HttpContext.Current.Request; |
057 |
HttpFileCollection File = Request.Files; |
058 |
HttpPostedFile PostFile = File[FormField]; |
061 |
this .CheckingType(PostFile.FileName); |
064 |
var Path = this .GetPath(); |
065 |
var dir = Path + this .FileInfo[ "Name" ]; |
068 |
this .FileInfo.Add( "path" , Path + this .FileInfo[ "Name" ]); |
069 |
this .FileInfo.Add( "filepath" , this .FileInfo[ "dir" ] + this .FileInfo[ "Name" ]); |
072 |
PostFile.SaveAs(dir); |
078 |
/// <returns></returns> |
079 |
private string GetPath() |
082 |
string Path = this .FilePath; |
085 |
string Date = DateTime.Now.ToString( "yyyy-MM/dd" ); |
086 |
string dir = HttpContext.Current.Server.MapPath(Path + "/" + Date); |
089 |
this .FileInfo.Add( "dir" , Date + '/' ); |
092 |
if (Directory.Exists(dir) == false ) |
093 |
Directory.CreateDirectory(dir); |
100 |
/// <param name="FileName"></param> |
101 |
private void CheckingType( string FileName) |
104 |
string [] TypeList = this .FileType.Split( ',' ); |
107 |
string Type = Path.GetExtension(FileName).ToLowerInvariant(); |
108 |
string Name = Path.GetFileNameWithoutExtension(FileName); |
109 |
string NameHash = Name.GetHashCode().ToString(); |
112 |
this .FileInfo.Add( "name" , Name); |
113 |
this .FileInfo.Add( "Name" , MD5.Encrypt(NameHash) + Type); |
114 |
this .FileInfo.Add( "type" , Type); |
117 |
if (TypeList.Contains(Type) == false ) |
118 |
this .TryError( "文件類型非法!" ); |
124 |
/// <param name="Msg"></param> |
125 |
public void TryError( string Msg) |
用法:
1 |
var Upload = new UploadFile(); |
4 |
Response.Write(Upload.Message); |
6 |
Response.Write(Upload.FileInfo[ "filepath" ]); |
7 |
Response.Write( "上傳成功!" ); |
|