public partial class DownloadFile : System.Web.UI.Page
{
private string sysID = "AM50";
protected void Page_Load(object sender, EventArgs e)
{
string downfileid = LZFormat.Null2String(Request.QueryString["fileid"]);
string downfiletable = LZFormat.Null2String(Request.QueryString["filetable"]);
string downfilefield = LZFormat.Null2String(Request.QueryString["filefield"]);
bool issuccess = false;
//根据文件附件id获取附件信息
List<Hashtable> htlist = GetFileDataTable(downfileid, downfiletable);
if (htlist.Count == 1)
{
//下载单条记录
issuccess = downLoadSingleFile(htlist[0], downfilefield);
}
else if (htlist.Count > 1)
{
//下载多条记录
issuccess = downLoadMultiFile(htlist, downfilefield);
}
else
{
//没有要下载的附件信息
//spanErrorInfo.InnerText = "文件下载失败!请检查文件是否存在。";
}
}
#region 根据文件id集合获取文件信息
/// <summary>
/// 根据文件id集合获取文件信息
/// </summary>
/// <param name="downfileid"></param>
/// <param name="downfiletable"></param>
/// <returns></returns>
protected List<Hashtable> GetFileDataTable(string downfileid, string downfiletable)
{
List<Hashtable> htlist = new List<Hashtable>();
DataTable dt = new DataTable();
using (Database oBase = DatabaseFactory.CreateDatabase(sysID))
{
string sql = "select * from " + downfiletable + " where charindex(FileID,'" + downfileid + "')>0";
DbCommand cmd = oBase.GetSqlStringCommand(sql);
dt = oBase.ExecuteDataTable(cmd);
}
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
Hashtable ht = new Hashtable();
foreach (DataColumn column in dt.Columns)
{
ht[column.ColumnName] = row[column.ColumnName];
}
htlist.Add(ht);
}
}
return htlist;
}
#endregion
#region 下载单个文件
/// <summary>
/// 下载单个文件
/// </summary>
/// <param name="ht">下载文件信息</param>
/// <param name="downfilefield">需要下载的文件字段</param>
/// <returns></returns>
private bool downLoadSingleFile(Hashtable ht, string downfilefield)
{
bool isSuccess = false;
string RelativePath = LZFormat.Null2String(ht["RelativePath"]);
String FileName = LZFormat.Null2String(ht["FileName"]);
String PartitionID = LZFormat.Null2String(ht["PartitionID"]);
String fileLocalName = LZFormat.Null2String(ht[downfilefield]);
String targetFilePath = "CommonModel/CommonFTPLoad/FileReaponseDownLoad/CacheFile";
targetFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, targetFilePath);//站点临时文件夹路径
isSuccess = FtpDownLoadToLocal(RelativePath, fileLocalName, targetFilePath, PartitionID);
if (isSuccess && File.Exists(targetFilePath + "\\" + fileLocalName))
{
isSuccess = this.TranDownLoad(targetFilePath, fileLocalName, fileLocalName);
}
return isSuccess;
}
#endregion
#region 使用TransmifFile下载文件
/// <summary>
/// 使用TransmifFile下载文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称</param>
/// <param name="downLoadFileName">下载到客户端的文件名称</param>
/// <returns></returns>
private bool TranDownLoad(string filePath, string fileName, string downLoadFileName)
{
try
{
filePath = filePath + "/" + fileName;
if (File.Exists(filePath))
{
FileInfo info = new FileInfo(filePath);
long fileSize = info.Length;
System.Web.HttpContext.Current.Response.Clear();
if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
{
Response.AddHeader("Content-Disposition", "attachment; filename=" + downLoadFileName + "");
}
else
{
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(downLoadFileName, System.Text.Encoding.UTF8).Replace("+", " ") + "");
}
Response.AddHeader("Content-Length", fileSize.ToString());
Response.ContentType = this.GetFileContentType(fileName);
Response.WriteFile(filePath);
//System.Web.HttpContext.Current.Response.End();
return true;
}
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, LZExceptionType.System, " - FtpDownLoadToLocal使用Ftp下载至本地");
return false;
}
return false;
}
#endregion
#region 从FTP服务器下载到站点服务器
/// <summary>
/// 从FTP服务器下载到站点服务器
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称</param>
/// <param name="targetFilePath">存储路径</param>
/// <param name="partionID">存储区id</param>
/// <returns></returns>
public bool FtpDownLoadToLocal(String filePath, String fileName, String targetFilePath, String partionID)
{
if (!Directory.Exists(targetFilePath + "\\"))
{
Directory.CreateDirectory(targetFilePath + "\\");
}
Hashtable htFtp = this.GetFtpServerInfoByApid(partionID);
String ftpServerIP = LZFormat.Null2String(htFtp["AUS_ServerName"]);
String ftpUserID = LZFormat.Null2String(htFtp["AUS_LogInUserName"]);
String ftpPassword = LZFormat.Null2String(htFtp["AUS_LogInUserPwd"]);
String ftpPort = LZFormat.Null2String(htFtp["AUS_ServerPort"]);
String ftpReleatPath = LZFormat.Null2String(htFtp["AP_FTPRelatPath"]);
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + ":" + ftpPort + "/" + ftpReleatPath.Replace(@"\", @"/") + "/" + filePath.Replace(@"\", @"/") + "/" + LZUtils.FtpFileNameEncodeSpecialCharacter(fileName)));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
FileStream outputStream = new FileStream(targetFilePath + "\\" + fileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, LZExceptionType.System, " - FtpDownLoadToLocal使用Ftp下载至本地");
return false;
}
return true;
}
#endregion
#region 获取文件流类型
private string GetFileContentType(string filedownloadname)
{
string DEFAULT_CONTENT_TYPE = "application/octet-stream";
RegistryKey regkey, fileextkey;
string FileContentType;
try
{
regkey = Registry.ClassesRoot;
fileextkey = regkey.OpenSubKey(this.GetFileExtName(filedownloadname, false));
FileContentType = fileextkey.GetValue("Content Type", DEFAULT_CONTENT_TYPE).ToString();
}
catch
{
FileContentType = DEFAULT_CONTENT_TYPE;
}
return FileContentType;
}
#endregion
#region 获取文件扩展名
private string GetFileExtName(string filename, bool withdot)
{
string[] arrs = filename.Split('.');
int i = arrs.Length;
return withdot ? "." + arrs[i - 1].ToString() : arrs[i - 1].ToString();
}
#endregion
#region 改名
public string ReFileName(string fileName, string parentPath) { if (File.Exists(parentPath + fileName)) { int i = fileName.LastIndexOf("."); string frontStr = fileName.Substring(0, i); string lastStr = fileName.Substring(i, fileName.Length - i); frontStr = frontStr + "[重名]"; fileName = frontStr + lastStr; fileName = ReFileName(fileName, parentPath); } return fileName; }
#endregion
#region 压缩
public bool Zip(string zipfilePath)
{
int n = zipfilePath.LastIndexOf('\\');
string targetPath = zipfilePath.Substring(0, n);
string sourceName = zipfilePath.Substring(n + 1);
LZZip zip = new LZZip();
string result = Path.Combine(targetPath, sourceName + ".zip");
zip.ZipDirectory(result, targetPath + "\\" + sourceName + "\\");
return true;
}
#endregion
#region 多文件下载
private bool downLoadMultiFile(List<Hashtable> htlist, string downfilefield)
{
bool isSuccess = false;
try
{
string targetPath = @"C:\Windows\Temp\附件批量临时\";//临时目录 ,缓存数据
string timeFileName = DateTime.Now.ToString("yyyyMMddHHssmmfff");
string guidFileName = Guid.NewGuid().ToString();
string zipFileName = timeFileName + guidFileName;
string zipPath = targetPath + zipFileName;
Directory.CreateDirectory(zipPath);
for (int i = 0; i < htlist.Count; i++)
{
Hashtable ht = htlist[i];
string RelativePath = LZFormat.Null2String(ht["RelativePath"]);
String FileName = LZFormat.Null2String(ht["FileName"]);
String PartitionID = LZFormat.Null2String(ht["PartitionID"]);
String fileLocalName = LZFormat.Null2String(ht[downfilefield]);
String SrcFileName = fileLocalName;
fileLocalName = ReFileName(fileLocalName, zipPath + "\\");//下载的文件中名称相同时,要改
isSuccess = FtpDownLoadToLocal(RelativePath, SrcFileName, zipPath, PartitionID, fileLocalName);
if (!isSuccess) return isSuccess;
}
Zip(zipPath);
Directory.Delete(zipPath, true);//压缩完后删除临时文件夹
isSuccess = this.WriteFileDownLoad(targetPath, zipFileName + ".zip", timeFileName + ".zip");
File.Delete(targetPath + zipFileName + ".zip");//文件下载完后删除zip文件
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, 1, this.Description + " - 多文件下载");
flag = false;
}
return isSuccess;
}
#endregion
#region 从文件服务器下载到站点服务器
public bool FtpDownLoadToLocal(String filePath, String fileName, String targetFilePath, String partionID, String fileLocalName)
{
if (!Directory.Exists(targetFilePath + "\\"))
{
Directory.CreateDirectory(targetFilePath + "\\");
}
Hashtable htFtp = this.GetFtpServerInfoByApid(partionID);
String ftpServerIP = LZFormat.Null2String(htFtp["AUS_ServerName"]);
String ftpUserID = LZFormat.Null2String(htFtp["AUS_LogInUserName"]);
String ftpPassword = LZFormat.Null2String(htFtp["AUS_LogInUserPwd"]);
String ftpPort = LZFormat.Null2String(htFtp["AUS_ServerPort"]);
String ftpReleatPath = LZFormat.Null2String(htFtp["AP_FTPRelatPath"]);
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + ":" + ftpPort + "/" + ftpReleatPath.Replace(@"\", @"/") + "/" + filePath.Replace(@"\", @"/") + "/" + LZUtils.FtpFileNameEncodeSpecialCharacter(fileName)));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
FileStream outputStream = new FileStream(targetFilePath + "\\" + fileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, LZExceptionType.System, " - FtpDownLoadToLocal使用Ftp下载至本地");
return false;
}
return true;
}
#endregion
#region 输出流
public bool WriteFileDownLoad(string filePath, string fileName, string downLoadFileName)
{
filePath = filePath + "/" + fileName;
try
{
if (File.Exists(filePath))
{
byte[] buffer = new byte[1024L];
base.Response.Clear();
FileStream fileStream = File.OpenRead(filePath);
long num = fileStream.Length;
if (this.Context.Request.UserAgent.IndexOf("AppleWebKit") > 0)
{
this.Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + downLoadFileName);
}
else
{
this.Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(downLoadFileName, Encoding.UTF8).Replace("+", " "));
}
this.Context.Response.AddHeader("Content-Length", fileStream.Length.ToString());
this.Context.Response.ContentType = this.GetFileContentType(fileName);
while (num > 0L && base.Response.IsClientConnected)
{
int num2 = fileStream.Read(buffer, 0, Convert.ToInt32(1024L));
this.Context.Response.OutputStream.Write(buffer, 0, num2);
this.Context.Response.Flush();
num -= (long)num2;
}
fileStream.Close();
this.Context.Response.Close();
return true;
}
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, 1, this.Description + " - WriteFile文件流路径:" + filePath);
bool result = false;
return result;
}
return false;
}
#endregion
#region 获取存储区信息
private Hashtable GetFtpServerInfoByApid(string partionID)
{
try
{
Hashtable htFtpServerInfo = null;
using (Database db = DatabaseFactory.CreateDatabase(DbInstanceName.DOC.ToString()))
{
strSql = String.Format("SELECT LZMISCommon.dbo.AM_UploadServer.*,LZMISCommon.dbo.AM_Partitions.AP_FTPRelatPath from LZMISCommon.dbo.AM_UploadServer inner join LZMISCommon.dbo.AM_Partitions on LZMISCommon.dbo.AM_UploadServer.AUS_ID=AM_Partitions.AP_Server where LZMISCommon.dbo.AM_Partitions.AP_ID = '{0}'", partionID);
htFtpServerInfo = db.ExecuteHashtable(strSql);
}
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, 1, this.Description + " - 获取文件存储区配置信息时发生错误!:" + filePath);
throw;
}
}
#endregion
}