public class FileOperate
{
SQLServerDAL.TB_FILE fileSQL = new SQLServerDAL.TB_FILE();
Entity.TB_FILE fileEntity = new Entity.TB_FILE();//文件实体
PDFOperate PDFoperate = new PDFOperate();
private BLL.ManageSys.ftp ftpClient = new ftp();
private static readonly string WebFileTempStation = WebConfigurationManager.AppSettings["WebFileTempStation"]; //中转站路径
private static readonly string FtpUri = WebConfigurationManager.AppSettings["FtpUri"];//ftp 地址
// private BLL.ManageSys.FileOperate B_File = new BLL.ManageSys.FileOperate();
/// <summary>
/// 上传文件,并返回文件在数据库中的存储id,若没有要上传的文件,返回-1
/// 文件的显示名称为filename
/// 文件的存储名称为filename(去后缀)+日期(YYYYMMDD)+ 部门编码,如:各种注册码201211271300,
/// 其中“各种注册码”是去掉后缀文件名称,而20121127是日期,1300是部门编码
/// 文件路径为完整路径去掉文件名(带后缀的),
/// 如:D\\审计处\\
/// </summary>
/// <param name="fileUpload">文件上传控件</param>
/// <param name="strDirectory">相对应用程序所在文件的根目录的路径,
/// 如:应用程序(页面)所在路径为:E:\Projections of xa\projections\FAS\MSS\SpecialExpense,则根目录为"MSS",若要在MSS下新建文件夹“审计处”
/// 则应输入"审计处"
/// 若在根目录下新建多级文件夹,则,格式类似;“审计处\\经济责任审核”</param>
/// <param name="filename">文件名称,如:test.txt</param>
/// <param name="code">部门编码,若不用可为空</param>
/// <returns></returns>
public decimal UploadFile(FileUpload fileUpload, string strDirectory, string fileName ,decimal deptCode )
{
if (fileUpload.HasFile)
{
string name = fileUpload.PostedFile.FileName;//获取文件名称
int index = fileName.LastIndexOf(".");//filename
string lastName = fileName.Substring(index, fileName.Length - index);//文件后缀 包含. 起始位置 如.doc
string firstName = fileName.Substring(0, index);//文件除后缀之外的字符串
string internalName = firstName + DateTime.Now.ToString("yyyyMMddhhmmss") + deptCode.ToString() + lastName;//新文件名 = 文件名+yyyymmdd+部门编码
string internalNameWithOutLastname = internalName.Substring(0, internalName.LastIndexOf("."));
//MapPath("/")获得应用程序根目录所在的位置,如 E:\Projections of xa\projections\FAS\MSS
if (!Directory.Exists(WebFileTempStation + strDirectory))
{
Directory.CreateDirectory(WebFileTempStation + strDirectory);
}
//上传到中转站
fileUpload.SaveAs(WebFileTempStation + strDirectory + "\\" + internalName);
//creat ftp dir
string []ftpdirs = strDirectory.Split(new char []{'\\'});
string uri = new Uri(FtpUri).ToString();
foreach (string ftpdir in ftpdirs)
{
if ("" != ftpdir)
{
uri += ftpdir + "/";
}
}
if (!ftpClient.DirectoryExist(uri))
{
Uri UriPath = new Uri(FtpUri + "PartyOrganization(党组织管理系统)/");
ftpClient.MakeMutiDir(strDirectory,UriPath);
}
//上传到ftp
ftpClient.UploadFile(WebFileTempStation + strDirectory + "\\" + internalName, new Uri(FtpUri+"PartyOrganization(党组织管理系统)/" + strDirectory + ""), 0, WebRequestMethods.Ftp.UploadFile);
fileEntity.rounte = strDirectory;//相对文件中转站的文件路径,不包括文件名 如 党组织\入党申请
fileEntity.outerName = fileName;//显示名称 带后缀的
fileEntity.internalName = internalName;//内部名称,即存储名称 带后缀的
fileEntity.time = DateTime.Now.Date;//日期
fileEntity.deptcode = deptCode;//部门编号
//ym 上传的时候即转一份pdf 加 水印
if (lastName.ToLower() == ".doc" || lastName.ToLower() == ".docx")
{
PDFoperate.ConvertWordToPdf(WebFileTempStation + strDirectory + "\\" + internalName, WebFileTempStation + strDirectory + "\\" + internalNameWithOutLastname + ".pdf");
}
string pdfFullName = WebFileTempStation + strDirectory + "\\" + internalNameWithOutLastname + ".pdf";
FileInfo pdffile = new FileInfo(pdfFullName); // 如果存在pdf 则为全路径
if (pdffile.Exists)//存在pdf的话加水印
{
//while (!PDFoperate.CheckFileIsUse(pdfFullName))
//{
// System.Threading.Thread.Sleep(10);
//}
string str = "";
PDFoperate.AddTextWaterMark(WebFileTempStation + strDirectory + "\\" + internalNameWithOutLastname + ".pdf", ref str, DateTime.Now.ToString());
//上传到ftp
ftpClient.UploadFile(WebFileTempStation + strDirectory + "\\" + internalNameWithOutLastname + ".pdf", new Uri(FtpUri+"PartyOrganization(党组织管理系统)/" + strDirectory + ""), 0, WebRequestMethods.Ftp.UploadFile);
}
deleteFileMid(strDirectory + "\\" + internalName);//delete tempfile
deleteFileMid(strDirectory + "\\" + internalNameWithOutLastname + ".pdf");//delete temp pdf
return fileSQL.Add(fileEntity);
}
else
return -1;//
}
//
public string getupName(string path)
{
return path.Substring(0, path.LastIndexOf(@"\"));
}
/// <summary>
///
/// </summary>
/// <param name="fileName">相对中转站本系统根目录路径 如D;\ZC\dangzuzhi\ddd 后面的 dangzuzhi\ddd </param>
public void deleteFileMid(string fileName)
{
try
{
System.IO.File.Delete(WebFileTempStation + fileName);
}
catch
{
}
}
/// <summary>
/// 文件浏览/下载
/// </summary>
/// <param name="response">Response对象</param>
/// <param name="fileId">指定要删除的文件id</param>
/// <param name="fileName">文件名称,若filename不为空,则下载时显示的文件名称为filename,否则为默认的显示名称</param>
/// <returns></returns>
public bool DownLoadFile(HttpResponse response, decimal fileId, string fileName)
{
Entity.TB_FILE DownloadEntity = new Entity.TB_FILE();//文件实体
string FullFileName = "";//完整路径
string strFilename = "";//显示名称
string rounte = "";//路径
DownloadEntity = fileSQL.GetModel(fileId);
if (DownloadEntity != null)
{
rounte = DownloadEntity.rounte;//文件路径 相对中专站路径
if (fileName == "")
{
fileName = DownloadEntity.outerName;
}
// 从ftp 下载到 中转站
ftpClient.Download(DownloadEntity.rounte,DownloadEntity.rounte+ @"\" + DownloadEntity.internalName,new Uri(FtpUri+"PartyOrganization(党组织管理系统)/"));//
ftpClient.Download(DownloadEntity.rounte, DownloadEntity.rounte + @"\" + DownloadEntity.internalName.ToString().Substring(0, DownloadEntity.internalName.LastIndexOf(".")) + ".pdf"
, new Uri(FtpUri+"PartyOrganization(党组织管理系统)/"));//pdf
//从中转站下载到本地
//ym 下载为pdf
string filenamePDF = fileName.Substring(0, fileName.LastIndexOf(".")) + ".pdf";
string pdfName = DownloadEntity.internalName.ToString().Substring(0, DownloadEntity.internalName.LastIndexOf("."))+".pdf";//下载pdf用的。
FullFileName = WebFileTempStation+ rounte + "\\" + pdfName; //pdf文件的全名 从中转站下载
FileInfo DownloadFile = new FileInfo(FullFileName);
//源文件是非word或pdf的 就下载源文件
string FullFileName2 = WebFileTempStation + rounte + "\\" + DownloadEntity.internalName;
FileInfo DownloadFile2 = new FileInfo(FullFileName2);
if (DownloadFile.Exists) //ym 下载为pdf
{
response.Clear();
response.ClearHeaders();
response.Buffer = false;
response.ContentType = "application/octet-stream";
strFilename = HttpUtility.UrlEncode(System.Text.UTF8Encoding.UTF8.GetBytes(filenamePDF));//ManageSysSystem.Text.Encoding.ASCII
//strFilename = HttpUtility.UrlEncode(fileName, System.Text.Encoding.ASCII);
// response.AddHeader("content-type", "application/x-msdownload");
response.AppendHeader("Content-Disposition", "attachment;filename=" + strFilename);//strFilename是保存时要显示的名称
response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
response.WriteFile(DownloadFile.FullName);
response.Flush();
// response.End();//我用的时候,加上End()会报异常,所以我给注释掉了
deleteFileMid(rounte + "\\" + DownloadEntity.internalName);//delete tempfile
deleteFileMid(rounte + "\\" + DownloadEntity.internalName.ToString().Substring(0, DownloadEntity.internalName.LastIndexOf(".")) + ".pdf");//delete tempfile pdf
return true;
}
else if (DownloadFile2.Exists) //源文件是非word或pdf的 就下载源文件
{
response.Clear();
response.ClearHeaders();
response.Buffer = false;
response.ContentType = "application/octet-stream";
strFilename = HttpUtility.UrlEncode(System.Text.UTF8Encoding.UTF8.GetBytes(fileName));//ManageSysSystem.Text.Encoding.ASCII
//strFilename = HttpUtility.UrlEncode(fileName, System.Text.Encoding.ASCII);
//response.AddHeader("content-type", "application/x-msdownload");
response.AppendHeader("Content-Disposition", "attachment;filename=" + strFilename);//strFilename是保存时要显示的名称
response.AppendHeader("Content-Length", DownloadFile2.Length.ToString());
response.WriteFile(DownloadFile2.FullName);
response.Flush();
// response.End();//我用的时候,加上End()会报异常,所以我给注释掉了
deleteFileMid(rounte + "\\" + DownloadEntity.internalName);//delete tempfile
deleteFileMid(rounte + "\\" + DownloadEntity.internalName.ToString().Substring(0, DownloadEntity.internalName.LastIndexOf(".")) + ".pdf");//delete tempfile pdf
return true;
}
else
{
//文件不存在
return false;
}
}
else
return false;
}
/// <summary>
/// 删除服务器上指定的文件
/// </summary>
/// <param name="id">指定要删除文件的id</param>
/// <returns></returns>
public bool DeleteFile(decimal fileId)
{
Entity.TB_FILE DetelefileEntity = new Entity.TB_FILE();//文件实体
DetelefileEntity = fileSQL.GetModel(fileId);
if (DetelefileEntity != null)
{
string fileName = DetelefileEntity.rounte + "\\" + DetelefileEntity.internalName;
try
{
System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("/") + fileName);
fileSQL.Delete(fileId);//删除数据库中的记录
return true;
}
catch
{
return false;
}
}
else
{
return false;//不存在该记录
}
}
/// <summary>
/// 获得File的实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Entity.TB_FILE getFileEntity(decimal id)
{
return fileSQL.GetModel(id);
}
/// <summary>
/// 根据id更新文件
/// </summary>
/// <param name="fileUpload"></param>
/// <param name="id">要更新的文件的id</param>
/// <returns></returns>
public bool UpdateFile(FileUpload fileUpload, decimal id)
{
fileEntity = fileSQL.GetModel(id);
if (fileEntity != null && fileUpload.HasFile)
{
string fileName = fileEntity.rounte + "\\" + fileEntity.internalName;
try
{
System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("/") + fileName);
if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/") + "\\" + fileEntity.rounte))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/") + "\\" + fileEntity.rounte);
}
fileUpload.SaveAs(System.Web.HttpContext.Current.Server.MapPath("/") + "\\" + fileEntity.rounte + "\\" + fileEntity.internalName);
return true;
}
catch
{
return false;
}
}
else
{
return false;//不存在该记录
}
}
}