马上要过年了,现在也没有什么事情要做,今天就给大家讲讲基于WebService的文件上传,和下载,其实我们只是通过WebService来实现文件流的传输
下面说说我设计的文件上传系统
需求:
1.要可定制文件策略,也就是我可以允许系统上传什么格式的文件,每个格式文件允许多大 ,这些都可以通过后台来设定
2.上传文件的存储位置要支持多种,以便以后有所变动,目前支持有:数据库,Ftp,磁盘 三种存储介质
3. 更新同一个文件的时候,文件版本号自动变动,例如A文件 V1.0再次更新文件后版本号自动变为V1.1
4.文件被下载的时候,要有下载日志 ,用于记录文件的那个版本都被什么人下载过
数据库设计:
Files 文件表, 用于记录文件的主要信息,文件名,大小,版本号,上传人等信息
FileUpStrategy 文件上传策略表,用于设定可以上传的文件类型,大小等信息
FileContent 文件内容,用于支持数据库存储
FileContentType 文件内容类型 ,用于输出正确的文件流,例如:pdf格式的文件,内容类型 application/pdf 这个要在 Response.ContentType进行指定
FileDownLog 文件下载日志,用于记录下载日志的一些信息
FileScope 文件作用范围,这个标明文件的用途,可以和权限系统联系在一起,那个部门可以上传什么用途的文件
关键代码:
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Net;
using System.Configuration;
using NHibernate;
using NHibernate.Criterion;
using System.Web.Caching;
using System.Web;
using AdminNet.Model.FileManager;
using AdminNet.IBLL.FileManager;
using AdminNet.Common;
namespace AdminNet.BLL.FileManager
{
public class File : Common, IFile
{
#region 文件基本信息
#region 文件查询
private IList Find(DetachedCriteria dc)
{
BaseDaoInIt();
ObjectNotNull(dc);
IList temp;
try
{
temp = BaseDao.FindByDetachedCriteria(dc);
BaseDao.Clear();
}
catch (Exception ex)
{
throw new DcException( " 获取文件失败 " , ex);
}
return temp;
}
public IList FindFile(Dictionary < string , object > dic, int offSet, int maxSize)
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
if (offSet < 0 || maxSize < 0 )
{
throw new DcException( " offSet或maxSize不能小于0 " );
}
if (maxSize > 0 )
{
dc.SetFirstResult(offSet * maxSize);
dc.SetMaxResults(maxSize);
}
dc.AddOrder(Order.Desc( " CreateDate " ));
foreach (KeyValuePair < string , object > kvp in dic)
{
object o = kvp.Value;
if (o is string )
{
if ( ! isNullOrEmpty(kvp.Value.ToString()))
{
if (kvp.Key.Equals( " CreateDate " ))
{
string [] str = kvp.Value.ToString().Split( new char [] { ' ; ' });
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
if (DateTime.TryParse(str[ 0 ], out dt1) && DateTime.TryParse(str[ 1 ], out dt2))
{
dc.Add(Restrictions.Between(kvp.Key, dt1, dt2.AddDays( 1 )));
}
}
else
{
dc.Add(Restrictions.Like(kvp.Key, " % " + kvp.Value + " % " ));
}
}
}
if (o is int )
{
if (kvp.Key.Equals( " Id " ))
{
dc.Add(Restrictions.Eq(kvp.Key, stringToInt32(o.ToString())));
}
else
{
dc.Add(Restrictions.Ge(kvp.Key, stringToInt32(o.ToString())));
}
}
if (o is IList)
{
IList lt = o as IList;
dc.Add(Restrictions.In(kvp.Key, stringToInt32(lt)));
}
if (o is double )
{
dc.Add(Restrictions.Ge(kvp.Key, double .Parse(o.ToString())));
}
}
return Find(dc);
}
public int CountFile(Dictionary < string , object > dic)
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
dc.SetProjection(Projections.RowCount());
foreach (KeyValuePair < string , object > kvp in dic)
{
object o = kvp.Value;
if (o is string )
{
if ( ! isNullOrEmpty(kvp.Value.ToString()))
{
if (kvp.Key.Equals( " CreateDate " ))
{
string [] str = kvp.Value.ToString().Split( new char [] { ' ; ' });
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
if (DateTime.TryParse(str[ 0 ], out dt1) && DateTime.TryParse(str[ 1 ], out dt2))
{
dc.Add(Restrictions.Between(kvp.Key, dt1, dt2.AddDays( 1 )));
}
}
else
{
dc.Add(Restrictions.Like(kvp.Key, " % " + kvp.Value + " % " ));
}
}
}
if (o is int )
{
if (kvp.Key.Equals( " Id " ))
{
dc.Add(Restrictions.Eq(kvp.Key, stringToInt32(o.ToString())));
}
else
{
dc.Add(Restrictions.Ge(kvp.Key, stringToInt32(o.ToString())));
}
}
if (o is IList)
{
IList lt = o as IList;
dc.Add(Restrictions.In(kvp.Key, stringToInt32(lt)));
}
if (o is double )
{
dc.Add(Restrictions.Ge(kvp.Key, double .Parse(o.ToString())));
}
}
return stringToInt32(Find(dc)[ 0 ].ToString());
}
#endregion
#region 文件基本信息保存
public int Save(FM_FileInfo file)
{
int status = 0 ;
BaseDaoInIt();
ObjectNotNull(file);
Dictionary < string , object > dic = new Dictionary < string , object > ();
dic.Add( " FileDisplayName " , file.FileDisplayName);
dic.Add( " FileScope_Id " , file.FileScope_Id);
int count = CountFile(dic);
if (count > 0 )
{
status = - 4 ;
}
else
{
file.CreateDate = DBNow();
file.FileUpDate = file.CreateDate;
file.FileUpdateDate = file.FileUpDate;
try
{
BaseDao.Save(file);
FileStoreDeviceFactory.GetFileStoreDevice(file).Save(file);
status = 1 ;
}
catch (Exception ex)
{
throw new DcException( " 保存文件失败 " , ex);
}
}
return status;
}
#endregion
#region 修改文件
public int Update(FM_FileInfo file)
{
int status = 200 ;
BaseDaoInIt();
ObjectNotNull(file);
file.FileUpdateDate = DBNow();
file.FileVersion += 0.1 ;
try
{
BaseDao.Update(file);
FileStoreDeviceFactory.GetFileStoreDevice(file).Update(file);
UpdateFileContent(file);
}
catch (Exception ex)
{
throw new DcException( " 更新文件失败 " , ex);
}
return status;
}
#endregion
#region 删除文件
public int Delete(FM_FileInfo file)
{
int status = 200 ;
ObjectNotNull(file);
file.Flag = ( int )Flag.Delete;
file.DeleteDate = DBNow();
BaseDao.Update(file);
return status;
}
#endregion
private void UpdateFileContent(FM_FileInfo file)
{
FileStoreDeviceFactory.GetFileStoreDevice(file).Update(file);
}
#endregion
#region 文件内容
public byte [] FindFileContent(Dictionary < string , object > dic, int offSet, int maxSize, FM_FileDownLogInfo downLog)
{
byte [] fileContent = new byte [ 0 ];
IList lt = FindFile(dic, 0 , 1 );
if (lt != null && lt.Count > 0 )
{
FM_FileInfo ff = lt[ 0 ] as FM_FileInfo;
fileContent = FileStoreDeviceFactory.GetFileStoreDevice(ff).Find(ff);
if (fileContent != null )
{
downLog.File_Id = ff.Id;
downLog.FileNum = ff.FileNum;
Save(downLog);
}
}
return fileContent;
}
#endregion
#region 文件下载日志
#region
public IList FindFileLog(Dictionary < string , object > dic, int offSet, int maxSize)
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileDownLogInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
if (offSet < 0 || maxSize < 0 )
{
throw new DcException( " offSet或maxSize不能小于0 " );
}
if (maxSize > 0 )
{
dc.SetFirstResult(offSet * maxSize);
dc.SetMaxResults(maxSize);
}
foreach (KeyValuePair < string , object > kvp in dic)
{
dc.Add(Restrictions.Eq(kvp.Key, kvp.Value));
}
return Find(dc);
}
public void Save(FM_FileDownLogInfo fileDownLog)
{
BaseDaoInIt();
ObjectNotNull(fileDownLog);
try
{
Dictionary < string , object > dic = new Dictionary < string , object > ();
dic.Add( " Id " , fileDownLog.File_Id);
IList temp = FindFile(dic, 0 , 1 );
if (temp != null && temp.Count > 0 )
{
FM_FileInfo file = temp[ 0 ] as FM_FileInfo;
if (file != null )
{
file.FileDownNum += 1 ;
fileDownLog.FileName = file.FileDisplayName;
BaseDao.Update(file);
fileDownLog.FileDownVersion = file.FileVersion;
}
}
BaseDao.Save(fileDownLog);
}
catch (Exception ex)
{
throw new DcException( " 记录下载日志失败 " , ex);
}
}
#endregion
#region 统计个数
public int CountFileLog(Dictionary < string , object > dic)
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileDownLogInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
foreach (KeyValuePair < string , object > kvp in dic)
{
dc.Add(Restrictions.Eq(kvp.Key, kvp.Value));
}
dc.SetProjection(Projections.RowCount());
return stringToInt32(Find(dc)[ 0 ].ToString());
}
#endregion
#endregion
#region 文件作用范围
public IList FindFileScope()
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileScopeInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
return Find(dc);
}
public IList FindFileScope(IList fileScodeId)
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileScopeInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
dc.Add(Restrictions.In( " Id " , IlistToString(fileScodeId)));
return Find(dc);
}
#endregion
#region 文件类型
public Hashtable FindFileContentType()
{
if ( object .Equals(HttpRuntime.Cache[CacheKeys.FileContentType], null ))
{
Hashtable ht = new Hashtable();
try
{
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileContentTypeInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
IList temp = Find(dc);
foreach (FM_FileContentTypeInfo f in temp)
{
if ( ! ht.ContainsKey(f.FileType))
{
ht.Add(f.FileType.ToLower(), f.FileContentType);
}
}
HttpRuntime.Cache[CacheKeys.FileContentType] = ht; // 使用缓存
}
catch (Exception ex)
{
throw new DcException( " 获取文件类型失败 " , ex);
}
}
Hashtable httemp = HttpRuntime.Cache[CacheKeys.FileContentType] as Hashtable;
return httemp;
}
#endregion
#region 文件上传策略
public int FileUpStrategy(FM_FileInfo file)
{
int status = 0 ;
DetachedCriteria dc = DetachedCriteria.For( typeof (FM_FileUpStrategyInfo));
dc.Add(Restrictions.Eq( " Flag " , ( int )Flag.Normal));
dc.Add(Restrictions.Eq( " FileScopeDes " , file.Type));
dc.Add(Restrictions.Eq( " FileType " , file.FileType));
try
{
IList lt = Find(dc);
if (lt != null && lt.Count > 0 )
{
status = - 1 ;
foreach (FM_FileUpStrategyInfo ffus in lt)
{
if (ffus.FileLenght >= file.FileLenght || ffus.FileLenght.Equals( 0 ))
{
status = 1 ;
break ;
}
}
}
else
{
status = - 2 ;
}
}
catch
{
status = 0 ;
}
return status;
}
#endregion
#region 获取目前日期时间
private string Now()
{
StringBuilder sb = new StringBuilder();
DateTime dt = DateTime.Now;
sb.AppendFormat( " {0:0000}{1:00}{2:00}{3:00}{4:00}{5:00}{6:000} " , dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
return sb.ToString();
}
#endregion
}
}
using System.Collections.Generic;
using System.Text;
using AdminNet.IBLL.FileManager;
using AdminNet.Model.FileManager;
using AdminNet.Common;
namespace AdminNet.BLL.FileManager
{
public class FileStoreDeviceFactory
{
public static IFileStoreDevice GetFileStoreDevice(FM_FileInfo file)
{
IFileStoreDevice fsd = null ;
switch (file.FileUpType)
{
case ( int )FileUpType.Disk:
fsd = ServiceLoader.GetService( " FileDiskDeviceTrans " ) as IFileStoreDevice;
break ;
case ( int )FileUpType.DataBase:
fsd = ServiceLoader.GetService( " FileDataBaseDeviceTrans " ) as IFileStoreDevice;
break ;
case ( int )FileUpType.Ftp:
fsd = ServiceLoader.GetService( " FileFtpDeviceTrans " ) as IFileStoreDevice;
break ;
default :
fsd = ServiceLoader.GetService( " FileDiskDeviceTrans " ) as IFileStoreDevice;
break ;
}
return fsd;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Collections;
using NHibernate;
using NHibernate.Criterion;
using AdminNet.Common;
using AdminNet.Model.FileManager;
using AdminNet.IBLL.FileManager;
using System.Configuration;
using System.IO;
namespace AdminNet.BLL.FileManager
{
public class FileDiskDevice:Common,IFileStoreDevice
{
public int Save(FM_FileInfo file)
{
return SavetoDisk(file);
}
public int Update(FM_FileInfo file)
{
return SavetoDisk(file);
}
public byte [] Find(FM_FileInfo file)
{
return FindFromDisk(file);
}
private int SavetoDisk(FM_FileInfo file)
{
int status = 1 ;
string fileName = file.FileDateName;
string fileUpDisk = ConfigurationManager.AppSettings[ " UpFileDisk " ];
if ( ! System.IO.Directory.Exists(fileUpDisk))
{
System.IO.Directory.CreateDirectory(fileUpDisk);
}
if (System.IO.File.Exists(fileUpDisk + fileName))
{
System.IO.File.Delete(fileUpDisk + fileName);
}
if ( ! System.IO.File.Exists(fileUpDisk + fileName))
{
try
{
using (FileStream fs = System.IO.File.Create(fileUpDisk + fileName, file.FileContent.Length))
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(file.FileContent);
bw.Flush();
bw.Close();
fs.Close();
}
}
catch (Exception ex)
{
throw new DcException( " 保存文件失败 " , ex);
}
}
return status;
}
private byte [] FindFromDisk(FM_FileInfo file)
{
byte [] fileContent = new byte [ 0 ];
if (System.IO.File.Exists(file.FileUpUrl))
{
try
{
using (FileStream fs = System.IO.File.OpenRead(file.FileUpUrl))
{
BinaryReader br = new BinaryReader(fs);
fileContent = br.ReadBytes(file.FileLenght);
br.Close();
fs.Close();
}
}
catch (Exception ex)
{
throw new DcException( " 获取文件失败 " , ex);
}
}
return fileContent;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Collections;
using NHibernate;
using NHibernate.Criterion;
using AdminNet.Common;
using AdminNet.Model.FileManager;
using AdminNet.IBLL.FileManager;
namespace AdminNet.BLL.FileManager
{
public class FileFtpDevice:Common,IFileStoreDevice
{
public int Save(FM_FileInfo file)
{
return SavetoFtp( file);
}
public int Update(FM_FileInfo file)
{
return SavetoFtp(file);
}
public byte [] Find(FM_FileInfo file)
{
return FindFromFtp(file);
}
private int SavetoFtp(FM_FileInfo file)
{
int status = 1 ;
string fileName = file.FileDateName;
try
{
FtpHelper.UploadFile(fileName, file.FileContent);
}
catch (Exception ex)
{
throw new DcException( " 保存文件失败 " , ex);
}
return status;
}
private byte [] FindFromFtp(FM_FileInfo file)
{
byte [] fileContent = new byte [ 0 ];
string fileName = file.FileDisplayName + " . " + file.FileType;
if (isNullOrEmpty(file.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
try
{
fileContent = FtpHelper.DownloadFile(file.FileUpUrl, fileName, file.FileLenght);
}
catch (Exception ex)
{
throw new DcException( " 获取文件失败 " , ex);
}
return fileContent;
}
}
}
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Text;
using AdminNet.Model.FileManager;
using AdminNet.Agent.FileManagerAgent;
using AdminNet.Common;
/// <summary>
/// FileService 的摘要说明
/// </summary>
[WebService(Namespace = " http://202.196.65.57/ " )]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class FileService : BaseServices
{
public FileService()
{
// 如果使用设计的组件,请取消注释以下行
// InitializeComponent();
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="fileContent"> 文件内容二进制 </param>
/// <param name="FileOriginalName"> 文件原名 </param>
/// <param name="FileDisplayName"> 系统显示文件名 </param>
/// <param name="FileUpUsers"> 上传用户名 </param>
/// <param name="FileType"> 文件类型 </param>
/// <param name="FileUpUrl"> 存储介质为磁盘的路径 </param>
/// <param name="FileUpType"> 上传类型0磁盘1数据库2Ftp </param>
/// <param name="Remark"> 备注 </param>
/// <returns> 0上传失败1上传成功-1存在该文件名 </returns>
[WebMethod]
public int FileUp(Byte[] fileContent, string FileOriginalName, string FileDisplayName, int FileLenght, string FileUpUsers, string Type, int FileScopeId, string FileUpUrl, int FileUpType, string Remark)
{
int status = 0 ;
FM_FileInfo ff = new FM_FileInfo();
ff.FileContent = fileContent;
ff.FileOriginalName = FileOriginalName;
ff.FileDisplayName = FileDisplayName;
int lenght = ff.FileOriginalName.Length;
int temp = ff.FileOriginalName.LastIndexOf( ' . ' );
if (temp > 0 )
{
lenght = temp;
}
if ( string .IsNullOrEmpty(ff.FileDisplayName))
{
ff.FileDisplayName = ff.FileOriginalName.Substring( 0 , lenght);
}
ff.FileLenght = FileLenght;
ff.FileType = ff.FileOriginalName.Substring(lenght, ff.FileOriginalName.Length - lenght).Replace( " . " , "" );
ff.Type = Type;
ff.FileScope_Id = FileScopeId;
ff.FileUpUsers = FileUpUsers;
ff.FileDateName = Now() + " . " + ff.FileType;
if (FileUpType.Equals( 0 ))
{
string fileName = ff.FileDateName;
string fileUpDisk = ConfigurationManager.AppSettings[ " UpFileDisk " ];
if (String.IsNullOrEmpty(ff.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
ff.FileUpUrl = fileUpDisk + fileName;
}
if (FileUpType.Equals( 2 ))
{
string fileName = ff.FileDateName;
string fileUpFtp = ConfigurationManager.AppSettings[ " UpFileFtp " ];
if (String.IsNullOrEmpty(ff.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
ff.FileUpUrl = fileUpFtp + fileName;
}
ff.FileUpType = FileUpType;
ff.Remark = Remark;
try
{
// status = FileAgent.FileUpStrategy(ff);
// if (status.Equals(1))
// {
status = FileAgent.Save(ff);
// }
}
catch (DcException dc)
{
status = - 3 ;
WriteSystemLog(dc);
}
catch (Exception ex)
{
status = - 3 ;
WriteSystemLog( new DcException( " 文件上传失败 " , ex));
}
return status;
}
[WebMethod]
public byte [] FileDown( string fileName, string FileDownUsers, string FileDownUsersIp)
{
byte [] fileContent = null ;
Dictionary < string , object > dic = new Dictionary < string , object > ();
dic.Add( " FileDisplayName " , fileName);
try
{
FM_FileDownLogInfo ffd = new FM_FileDownLogInfo();
ffd.FileDownUsers = FileDownUsers;
ffd.FileDownUsersIp = FileDownUsersIp;
fileContent = FileAgent.FindFileContent(dic, 0 , 1 , ffd);
}
catch (DcException dc)
{
WriteSystemLog(dc);
}
catch (Exception ex)
{
WriteSystemLog( new DcException( " 文件下载失败 " , ex));
}
return fileContent;
}
[WebMethod]
public int FileUpStrategy( string FileOriginalName, string FileDisplayName, int FileLenght, string FileUpUsers, string Type, string FileUpUrl, int FileUpType)
{
int status = 0 ;
FM_FileInfo ff = new FM_FileInfo();
ff.FileOriginalName = FileOriginalName;
ff.FileDisplayName = FileDisplayName;
int lenght = ff.FileOriginalName.Length;
int temp = ff.FileOriginalName.LastIndexOf( ' . ' );
if (temp > 0 )
{
lenght = temp;
}
if ( string .IsNullOrEmpty(ff.FileDisplayName))
{
ff.FileDisplayName = ff.FileOriginalName.Substring( 0 , lenght);
}
ff.FileLenght = FileLenght;
ff.FileType = ff.FileOriginalName.Substring(lenght, ff.FileOriginalName.Length - lenght).Replace( " . " , "" );
ff.Type = Type;
ff.FileUpUsers = FileUpUsers;
if (FileUpType.Equals( 0 ))
{
string fileName = ff.FileDisplayName + " . " + ff.FileType;
string fileUpDisk = ConfigurationManager.AppSettings[ " UpFileDisk " ];
if (String.IsNullOrEmpty(ff.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
ff.FileUpUrl = fileUpDisk + fileName;
}
if (FileUpType.Equals( 2 ))
{
string fileName = ff.FileDisplayName + " . " + ff.FileType;
string fileUpFtp = ConfigurationManager.AppSettings[ " UpFileFtp " ];
if (String.IsNullOrEmpty(ff.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
ff.FileUpUrl = fileUpFtp + fileName;
}
ff.FileUpType = FileUpType;
status = FileAgent.FileUpStrategy(ff);
return status;
}
#region 获取目前日期时间
private string Now()
{
StringBuilder sb = new StringBuilder();
DateTime dt = DateTime.Now;
sb.AppendFormat( " {0:0000}{1:00}{2:00}{3:00}{4:00}{5:00}{6:000} " , dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
return sb.ToString();
}
#endregion
[WebMethod]
public int FileUpDate( int Id,Byte[] fileContent, int FileLenght, string FileUpdateUsers, string Type, int FileScopeId, string Remark, string userId, string userIp)
{
int status = 1 ;
Dictionary < string , object > dic = new Dictionary < string , object > ();
dic.Add( " Id " , Id);
IList lt = FileAgent.FindFile(dic, 0 , 1 );
if (lt != null && lt.Count > 0 )
{
FM_FileInfo ff = lt[ 0 ] as FM_FileInfo;
ff.Remark = Remark;
ff.Type = Type;
ff.FileScope_Id = FileScopeId;
ff.FileUpdateUsers = FileUpdateUsers;
ff.FileContent = fileContent;
ff.FileLenght = FileLenght;
ff.FileDateName = Now() + " . " + ff.FileType;
if (ff.FileUpType.Equals( 0 ))
{
string fileName = ff.FileDateName;
string fileUpDisk = ConfigurationManager.AppSettings[ " UpFileDisk " ];
if (String.IsNullOrEmpty(ff.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
ff.FileUpUrl = fileUpDisk + fileName;
}
if (ff.FileUpType.Equals( 2 ))
{
string fileName = ff.FileDateName;
string fileUpFtp = ConfigurationManager.AppSettings[ " UpFileFtp " ];
if (String.IsNullOrEmpty(ff.FileType))
{
fileName = fileName.Trim( new char [] { ' . ' });
}
ff.FileUpUrl = fileUpFtp + fileName;
}
try
{
WriteOperationLog(DBTableName.FM_FileInfo, ff, userId, userIp);
FileAgent.Update(ff);
}
catch (DcException dc)
{
WriteSystemLog(dc);
}
catch (Exception ex)
{
WriteSystemLog( new DcException( " 文件更新失败 " , ex));
}
}
return status;
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AdminNet.Common;
using AdminNet.Agent.FileManagerAgent;
public partial class FileManager_File_Up : BasePage
{
protected void Page_Load( object sender, EventArgs e)
{
if ( ! IsPostBack)
{
BindFileScope();
}
}
protected void btnFileUp_Click( object sender, EventArgs e)
{
string fileName = fileUpLoad.FileName;
if (fileName == null )
{
ShowMessage( " 请选择要上传的文件 " );
return ;
}
if (rtnFileUpType.SelectedIndex < 0 )
{
ShowMessage( " 请选择一种文件存储方式 " );
return ;
}
if (ddlFileScope.SelectedIndex < 0 )
{
ShowMessage( " 你没有可使用的文件用途 " );
return ;
}
byte [] fileContent = fileUpLoad.FileBytes;
int fileLenght = fileContent.Length;
if (fileLenght > 0 )
{
// fileContent = ZipHelper.Zip(fileContent);
string fileDisplay = tbDisplayName.Text;
string fileUpType = this .rtnFileUpType.SelectedValue;
string fileScope = ddlFileScope.SelectedItem.Text;
int fileScopeId = int .Parse(ddlFileScope.SelectedValue);
string fileRemark = tbRemark.Text;
FileService fileService = new FileService();
int status = fileService.FileUpStrategy(fileName, fileDisplay, fileLenght, UserName, fileScope, "" , int .Parse(fileUpType));
if (status.Equals( 1 ))
{
status = fileService.FileUp(fileContent, fileName, fileDisplay, fileLenght, UserName, fileScope,fileScopeId, "" , int .Parse(fileUpType), fileRemark);
}
ShowMessage(FileServiceReturn(status));
}
else
{
ShowMessage( " 系统不允许上传没有内容的文件 " );
}
}
#region 绑定文件作用范围
public void BindFileScope()
{
try
{
IList lt = FileAgent.FindFileScope(FileScopeId);
ddlFileScope.DataSource = lt;
ddlFileScope.DataTextField = " FileScopeDes " ;
ddlFileScope.DataValueField = " Id " ;
ddlFileScope.DataBind();
}
catch (DcException dc)
{
ShowMessage(dc);
}
catch (Exception ex)
{
ShowMessage( new DcException( " 绑定文件作用范围失败 " , ex));
}
}
#endregion
#region FileServiceReturn
private string FileServiceReturn( int code)
{
string str = " 未知系统代码 " ;
switch (code)
{
case - 4 :
str = " 对不起,系统已存在相同的文件名,请修改资源文件名后在上传 " ;
break ;
case - 3 :
str = " 对不起,文件上传失败,可能由于系统出现故障,或系统压力过大,可以尝试稍后上传 " ;
break ;
case - 2 :
str = " 对不起,不允许上传该格式的文件 " ;
break ;
case - 1 :
str = " 对不起,上传文件的长度超过了系统的要求 " ;
break ;
case 0 :
str = " 对不起,文件上传失败,可能由于系统出现故障,或系统压力过大,可以尝试稍后上传 " ;
break ;
case 1 :
str = " 文件上传成功 " ;
break ;
}
return str;
}
#endregion
}
private void Down( string fileName)
{
FileService fileService = new FileService();
int lenght = fileName.Length;
int temp = fileName.LastIndexOf( ' . ' );
if (temp > 0 )
{
lenght = temp;
}
string fileName1 = fileName.Substring( 0 , lenght);
byte [] fileContent = fileService.FileDown(fileName1, UserName, UserIp);
if (fileContent.Length > 0 )
{
// fileContent = ZipHelper.Unzip(fileContent);
if (fileContent.Length > 0 )
{
Response.ContentType = ContentTypes(fileName.Substring(lenght, fileName.Length - lenght).Replace( " . " , "" ));
Response.AddHeader( " Content-Disposition " , " attachment; filename= " + HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding( " Utf-8 " )));
Response.AddHeader( " Content-Length " , fileContent.Length.ToString());
Response.BinaryWrite(fileContent);
Response.End();
}
else
{
ShowMessage( " 系统不允许下载无内容的文件 " );
}
}
else
{
ShowMessage( " 对不起,文件已经被删除 " );
}
}
#endregion
#region ContentType
private string ContentTypes( string fileExtend)
{
string contentType = " application/octet-stream " ;
Hashtable ht = FileAgent.FindFileContentType();
if (ht != null )
{
if (ht.ContainsKey(fileExtend.ToLower()))
{
contentType = ht[fileExtend] as string ;
}
}
return contentType;
}
#endregion
注意:Asp.net 本身不能支持大容量的文件上传,如果要增加文件的上传大小,可以在Web.Config 中增加
<httpRuntime executionTimeout="300" maxRequestLength="2097150" useFullyQualifiedRedirectUrl="false"/>
一般文件在几十M的情况下,采用这样的代码比较好,例如Csdn中的下载模块,如果你的系统需要上传很大的文件,比如1G建议不用WebService来做,容易让系统崩溃
欢迎大家一起讨论,一起成长