You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1691 lines
82 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Web.Hosting;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Configuration;
using OT.Web.Ap_Code;
using Ionic.Zip;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using DBUtility;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace OT.Web.WS
{
/// <summary>
/// Summary description for ImageToolWebService
/// </summary>
[WebService(Namespace = "http://origetk.com.tw/FileManage")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class OrigtekFileManageWS : System.Web.Services.WebService
{
public string topfileroot = ConfigurationManager.AppSettings["TopFileRoot"];
public string fileroot = ConfigurationManager.AppSettings["FileRoot"];
public string IsEntity = ConfigurationManager.AppSettings["IsEntity"];
[WebMethod]
#region getFileRoot 取得實體路徑
public string getFileRoot()
{
try
{
string root = fileroot; //預設為實體路徑
string root_dir = topfileroot; //取得上層路徑資料夾
string top_root = ""; //用for迴圈找出top路徑
if (IsEntity == "N") //如果webconfig設定不為實體路徑就將虛擬路徑轉為實體路徑
{
root = System.Web.Hosting.HostingEnvironment.MapPath(fileroot);
}
if (string.IsNullOrEmpty(topfileroot) && IsEntity == "N")
{
root_dir = fileroot.Split('/')[fileroot.Split('/').Length - 2];
}
else if (string.IsNullOrEmpty(topfileroot) && IsEntity == "Y")
{
root_dir = fileroot.Split('\\')[fileroot.Split('\\').Length - 2];
}
for (int path_count = 0; path_count < root.Split('\\').Length; path_count++)
{
if (root.Split('\\')[path_count] != root_dir)
{
//如果迴圈還沒跑到上層路徑
top_root += root.Split('\\')[path_count] + "\\";
}
else
{
//如果找到上層路徑跳出迴圈
break;
}
}
return top_root;
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region GetDeleteDirectory 取得刪除資料夾的預設名稱
public string GetDeleteDirectory()
{
string RemoveDirectory = ConfigurationManager.AppSettings["DeleteDirectory"];
return !string.IsNullOrEmpty(RemoveDirectory) ? RemoveDirectory : "Delete";
}
#endregion
#region getFileRoot_WebMethod 取得實體路徑
[WebMethod]
public string getFileRoot_WebMethod()
{
try
{
string root = fileroot; //預設為實體路徑
string root_dir = topfileroot; //取得上層路徑資料夾
string top_root = ""; //用for迴圈找出top路徑
if (IsEntity == "N") //如果webconfig設定不為實體路徑就將虛擬路徑轉為實體路徑
{
root = System.Web.Hosting.HostingEnvironment.MapPath(fileroot);
}
if (string.IsNullOrEmpty(topfileroot) && IsEntity == "N")
{
root_dir = fileroot.Split('/')[fileroot.Split('/').Length - 2];
}
else if (string.IsNullOrEmpty(topfileroot) && IsEntity == "Y")
{
root_dir = fileroot.Split('\\')[fileroot.Split('\\').Length - 2];
}
for (int path_count = 0; path_count < root.Split('\\').Length; path_count++)
{
if (root.Split('\\')[path_count] != root_dir)
{
//如果迴圈還沒跑到上層路徑
top_root += root.Split('\\')[path_count] + "\\";
}
else
{
//如果找到上層路徑跳出迴圈
break;
}
}
return "{\"top_root\":\"" + top_root + "\"}";
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region getTopDirectory 取得根目錄資料夾
public string getTopDirectory()
{
try
{
string NewFileRoot = getFileRoot();
string FullRoot = NewFileRoot;
if (IsEntity == "N")
{
FullRoot = System.Web.Hosting.HostingEnvironment.MapPath(fileroot);
}
//string[] arr_dir = NewFileRoot.Split('\\');
//string dir = arr_dir[arr_dir.Length - 2];
//return dir;
return FullRoot.Replace(NewFileRoot, "");
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region CreateDir 創建資料夾
[WebMethod]
public int CreateDir(string PUID, string filepath, string dirName, string OrganizeID, string UserID)
{
filepath = HttpUtility.UrlDecode(filepath, System.Text.Encoding.UTF8);
dirName = HttpUtility.UrlDecode(dirName, System.Text.Encoding.UTF8);
string p_path = getFileRoot(); //判斷實體路徑是否存在
try
{
p_path += filepath + dirName;
p_path = p_path.Replace("/", "\\");
if (Directory.Exists(@p_path)) //判斷資料夾是否存在,存在true 不存在false
{
return 1; //狀態1 路徑已經存在
}
else
{
try
{
BLL.OTB_SYS_Document otb_sys_document_bll = new BLL.OTB_SYS_Document();
Model.OTB_SYS_Document otb_sys_document_model = new Model.OTB_SYS_Document();
otb_sys_document_model.GUID = Guid.NewGuid().ToString();
otb_sys_document_model.PUID = PUID;
otb_sys_document_model.FileName = dirName;
otb_sys_document_model.FileRoot = filepath;
otb_sys_document_model.FilePath = filepath + dirName + "/";
otb_sys_document_model.CreateUser = UserID;
otb_sys_document_model.Organization = OrganizeID;
if (otb_sys_document_bll.AddDirectory(otb_sys_document_model))
{
Directory.CreateDirectory(@p_path);
return 2; //狀態2 創建資料夾成功
}
else
{
return 3; //狀態3 創建資料夾失敗
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error("CreateDirectory checkDir Error:" + ex + "\nFilePath:" + p_path);
return 3; //狀態3 創建資料夾失敗
}
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error("CreateDirectory checkDir Error:" + ex + "\nFilePath:" + p_path);
return 0; //狀態0 例外錯誤
}
}
#endregion
#region CheckFileExists 檢查上傳檔案是否已經存在 目前沒有使用
[System.Web.Services.WebMethod]
public bool CheckFileExists(string filepath, string fileName, string fileType)
{
filepath = HttpUtility.UrlDecode(filepath, System.Text.Encoding.UTF8);
fileName = HttpUtility.UrlDecode(fileName, System.Text.Encoding.UTF8);
string FileRoot = "";
try
{
if (Directory.Exists(System.Web.Hosting.HostingEnvironment.MapPath("~/DMImg/")))
{
FileRoot = System.Web.Hosting.HostingEnvironment.MapPath("~/") + filepath.Substring(1).Replace("/", "\\");
}
else
{
FileRoot = "E:\\ImageRoot" + filepath.Replace("/", "\\");
}
return File.Exists(FileRoot + fileName + "." + fileType); //返回true:存在 , false:不存在
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex);
return false; //儲存成功傳回false
}
}
#endregion
#region RenameDir 資料夾重新命名
[WebMethod]
public string RenameDir(string GUID, string filepath, string dirName, string user)
{
filepath = HttpUtility.UrlDecode(filepath, System.Text.Encoding.UTF8);
dirName = HttpUtility.UrlDecode(dirName, System.Text.Encoding.UTF8);
string p_path = getFileRoot(); //判斷實體路徑是否存在
string[] arr_path; //分割路徑字串找出資料夾名稱
string ori_dir_name = ""; //儲存原始資料夾名稱
string dir = getTopDirectory(); //取得webconfig設定的資料夾名稱
string dir_name = ""; //儲存資料夾名稱
//string fileroot = "/" + dir + "/" + filepath; //根目錄路徑
OT.BLL.OTB_SYS_Document otb_sys_document_bll = new OT.BLL.OTB_SYS_Document();
DataTable dt = new DataTable();
dt.Columns.Add("status", typeof(String));
dt.Columns.Add("curr_path", typeof(String));
DataRow dr = dt.NewRow();
try
{
user = user == "undefined" ? "admin" : user;
arr_path = filepath.Split('/');
//dir_name = arr_path[arr_path.Length - 2];
arr_path[arr_path.Length - 2] = dirName;
//last_inedx = filepath.LastIndexOf('/');
ori_dir_name += p_path + filepath.Replace("/", "\\");
//p_path = ori_dir_name.Replace("\\" + dir_name, "\\" + dirName);
p_path += string.Join("\\", arr_path);
if (Directory.Exists(p_path)) //判斷資料夾是否存在,存在true 不存在false
{
dr["status"] = "1";
//return 1; //狀態1 路徑已經存在
}
else
{
try
{
//Directory.CreateDirectory(p_path);
//DirectoryInfo di = new DirectoryInfo(ori_dir_name);
//DirectorySecurity diSecurity = Directory.GetAccessControl(HostingEnvironment.MapPath("~/"));
//SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
//diSecurity.AddAccessRule(new FileSystemAccessRule(@"Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
//Directory.SetAccessControl(HostingEnvironment.MapPath("~/"), diSecurity);
//di.MoveTo(p_path);
Directory.Move(ori_dir_name, p_path);
string NewPath = string.Join("/", arr_path);
//otb_sys_document_bll.DirectoryRename(GUID, dirName, filepath, filepath.Replace("/" + dir_name + "/", "/" + dirName + "/"), user);
otb_sys_document_bll.DirectoryRename(GUID, dirName, filepath, NewPath, user);
dr["status"] = "2";
dr["curr_path"] = NewPath.Replace("/" + dir, "");
//return 2; //狀態2 資料夾命名成功
}
catch (Exception ex)
{
BasePage.mo_Log.Error("CreateDirectory checkDir Error:" + ex + "\nFilePath:" + p_path);
dr["status"] = "3";
//return 3; //狀態3 資料夾命名失敗
}
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error("CreateDirectory checkDir Error:" + ex + "\nFilePath:" + p_path);
dr["status"] = "0";
//return 0; //狀態0 例外錯誤
}
dt.Rows.Add(dr);
return JsonConvert.SerializeObject(dt, Formatting.Indented);
}
#endregion
#region MoveFolder 移動資料夾
[WebMethod]
public bool MoveFolder(string PathName, string TargetName, string ModifyUser)
{
PathName = HttpUtility.UrlDecode(PathName, System.Text.Encoding.UTF8);
TargetName = HttpUtility.UrlDecode(TargetName, System.Text.Encoding.UTF8);
string[] arrFolderName = PathName.Split('/');
string FolderName = arrFolderName[arrFolderName.Length - 2]; //原始檔案路徑,做為更換檔名的條件
string FileRoot = getFileRoot(); //原始路徑
string TopRoot = ""; //路徑根目錄
string replaceString = TargetName + FolderName + "/"; //要取代的文字
string orifilepath; //原始檔案路徑,作為判斷資料庫更新條件
string[] fs; //分割完整路徑字串
string filename; //找出檔案名稱 xxx.jpeg
string newfilename = ""; //更新後的檔案名稱
string[] fls; //找出檔案名稱及副檔名
string fn = ""; //找出檔案名稱
string subfn; //找出附檔名
try
{
OT.BLL.OTB_SYS_Document otb_sys_document_bll = new OT.BLL.OTB_SYS_Document();
ModifyUser = ModifyUser == "undefined" ? "admin" : ModifyUser;
TopRoot = FileRoot;
FileRoot += PathName.Replace("/", "\\");
string NewPath = TopRoot + (TargetName + FolderName).Replace("/", "\\");
string TopPath = (TopRoot + TargetName).Replace("/", "\\");
DirectoryInfo di = new DirectoryInfo(FileRoot);
#region 資料夾移動
if (!Directory.Exists(NewPath))
{
DirectoryInfo top_di = new DirectoryInfo(TopPath);
top_di.CreateSubdirectory(FolderName.Replace("/", ""));
}
foreach (System.IO.DirectoryInfo di_child in di.GetDirectories("*", SearchOption.AllDirectories))
{
try
{
string path = di_child.FullName.Replace(PathName.Replace("/", "\\"), replaceString.Replace("/", "\\"));
if (!Directory.Exists(path))
{
//NewPath + path.Replace(NewPath, "").Replace(di_child.Name, "")
string spath = "";
string[] arr_path = (path.Replace(NewPath, "")).Split('\\');
for (int path_count = 0; path_count < arr_path.Length - 1; path_count++)
{
if (path_count == 0)
{
spath += arr_path[path_count];
}
else
{
spath += "\\" + arr_path[path_count];
}
}
DirectoryInfo dis = new DirectoryInfo(spath);
dis.CreateSubdirectory(di_child.Name);
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error("Document Create Error:" + ex + "\nDirectoryName: " + di_child.Name);
}
}
#endregion
#region 檔案移動
foreach (System.IO.FileInfo fi in di.GetFiles("*", SearchOption.AllDirectories).OrderBy(p => p.Name))
{
string FilePath = "";
string NewFilepath = "";
FilePath = fi.FullName;
NewFilepath = fi.FullName.Replace(PathName.Replace("/", "\\"), replaceString.Replace("/", "\\"));
orifilepath = fi.FullName;
try
{
if (!File.Exists(@NewFilepath))
{
fs = fi.FullName.Split('\\'); //分割完整路徑字串
filename = fs[fs.Length - 1]; //找出檔案名稱 xxx.jpeg
newfilename = filename; //更新後的檔案名稱
fls = filename.Split('.'); //找出檔案名稱及副檔名
fn = "";
//for迴圈主要避免檔案名稱有(.)導致檔案名稱被分割
for (int count = 0; count < fls.Length - 1; count++)
{
fn += fls[count];
}
File.Move(@FilePath, @NewFilepath);
}
else
{
fs = fi.FullName.Split('\\'); //分割完整路徑字串
filename = fs[fs.Length - 1]; //找出檔案名稱 xxx.jpeg
newfilename = ""; //更新後的檔案名稱
fls = filename.Split('.'); //找出檔案名稱及副檔名
fn = ""; //找出檔案名稱
subfn = fls[fls.Length - 1]; //找出附檔名
//for迴圈主要避免檔案名稱有(.)導致檔案名稱被分割
for (int count = 0; count < fls.Length - 1; count++)
{
fn += fls[count];
}
fn += "_複製"; //檔案名稱重複加上"_複製"
newfilename = fn + "." + subfn; //新檔案名稱
NewFilepath = NewFilepath.Replace(filename, newfilename);
File.Move(@fi.FullName, @NewFilepath);
}
string NewFileRoot = "";
orifilepath = orifilepath.Replace(TopRoot, "/").Replace("\\", "/"); //原始的路徑
NewFilepath = NewFilepath.Replace(TopRoot, "/").Replace("\\", "/"); //更新後的路徑
NewFileRoot = NewFilepath.Replace(newfilename, ""); //檔案根目錄
otb_sys_document_bll.DirMove(orifilepath, fn, NewFileRoot, NewFilepath, ModifyUser); //更新資料庫
}
catch (Exception ex)
{
BasePage.mo_Log.Error("FileMove Error:" + ex + "\nFilePath: " + NewFilepath);
}
}
#endregion
#region 移除原本資料夾
try
{
if (di.GetFiles().Count() == 0) //當檔案完全被移除後才刪除資料夾
{
di.Delete(true);
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error("DirectoryDelete Error:" + ex + "\nFilePath: " + FileRoot);
}
#endregion
return true;
}
catch (Exception ex)
{
BasePage.mo_Log.Error("Document MoveFolder Error:" + ex + "\nFilePath: " + FileRoot);
return false;
}
}
#endregion
#region MoveFolderToDB 移動資料夾更新資料庫
[WebMethod]
public string MoveFolderToDB(string Organization, string originPath, string targetPath, string originFID, string targetFID)
{
try
{
originPath = HttpUtility.UrlDecode(originPath, System.Text.Encoding.UTF8);
targetPath = HttpUtility.UrlDecode(targetPath, System.Text.Encoding.UTF8);
System.Text.StringBuilder strSql = new System.Text.StringBuilder();
strSql.Append(" update OTB_SYS_Document ");
strSql.Append(" set [PUID] = @targetFID ");
strSql.Append(" ,[FilePath] = REPLACE([FilePath],[FileRoot],@targetPath) ");
strSql.Append(" ,[FileRoot] = REPLACE([FileRoot],[FileRoot],@targetPath) ");
strSql.Append(" where [GUID] = @originFID and FileType = 'Directory' ");
strSql.Append(" declare @path nvarchar(500) ");
strSql.Append(" select @path = FilePath from OTB_SYS_Document where [GUID] = @originFID and FileType = 'Directory' ");
strSql.Append(" update OTB_SYS_Document ");
strSql.Append(" set [FilePath] = REPLACE([FilePath],'" + originPath + "',@path) ");
strSql.Append(" ,[FileRoot] = REPLACE([FileRoot],'" + originPath + "',@path) ");
strSql.Append(" where [FileRoot] like @originPath and FileType = 'Directory' ");
SqlParameter[] parameters = {
new SqlParameter("@OrganizationID", SqlDbType.NVarChar,50),
new SqlParameter("@originFID", SqlDbType.Char,36),
new SqlParameter("@targetFID", SqlDbType.Char,36),
new SqlParameter("@originPath", SqlDbType.NVarChar,500),
new SqlParameter("@targetPath", SqlDbType.NVarChar,500)
};
parameters[0].Value = Organization;
parameters[1].Value = originFID;
parameters[2].Value = targetFID;
parameters[3].Value = originPath + "%";
parameters[4].Value = targetPath;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return "1";
}
else
{
return "0";
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "0";
}
}
#endregion
#region checkFilePath 批次更名檔案命名檢查
[WebMethod]
public bool checkFilePath(string filename, string filepath)
{
filename = HttpUtility.UrlDecode(filename, System.Text.Encoding.UTF8);
filepath = HttpUtility.UrlDecode(filepath, System.Text.Encoding.UTF8);
string FileRoot = getFileRoot(); //儲存檔案路徑
string path = ""; //路徑
bool isFileExists = false; //檔案是否存在 預設false不存在
string[] arr_filename = filename.Split('/'); //分割檔案名稱字串
try
{
for (int filecount = 0; filecount < arr_filename.Length; filecount++)
{
path = (FileRoot + filepath + arr_filename[filecount]).Replace("/", "\\");
if (File.Exists(@path)) //如果檔案存在跳出迴圈
{
isFileExists = true;
break;
}
}
return isFileExists;
}
catch (Exception ex)
{
BasePage.mo_Log.Error("Document checkFilePath Error:" + ex + "\nFilePath: " + filepath + filename);
return true;
}
}
#endregion
#region SingleFileMove 單檔、批次移動
[WebMethod]
public bool SingleFileMove(string guid, string filename, string filepath, string targetpath, string ModifyUser)
{
filename = HttpUtility.UrlDecode(filename, System.Text.Encoding.UTF8);
filepath = HttpUtility.UrlDecode(filepath, System.Text.Encoding.UTF8);
targetpath = HttpUtility.UrlDecode(targetpath, System.Text.Encoding.UTF8);
string FileRoot = getFileRoot(); //儲存檔案路徑
//來源路徑及目標路徑
string oripath = FileRoot + filepath.Replace("/", "\\") + filename;
string tarpath = FileRoot + targetpath.Replace("/", "\\") + filename;
try
{
OT.BLL.OTB_SYS_Document otb_sys_document_bll = new OT.BLL.OTB_SYS_Document();
ModifyUser = ModifyUser == "" ? "admin" : ModifyUser;
//處理檔案名稱重組 start
int count = 1;
string[] arr_filename = filename.Split('.');
//for迴圈處理檔名有點時被分割錯誤導致檔名不正確
for (int intCount = 0; intCount < arr_filename.Length - 1; intCount++)
{
if (intCount == 0)
{
filename = arr_filename[intCount];
}
else
{
filename += "." + arr_filename[intCount];
}
}
//處理檔案名稱重組 end
if (!File.Exists(tarpath))
{
File.Move(oripath, tarpath);
}
else
{
do
{
filename += "_移動" + count.ToString();
tarpath = FileRoot + targetpath.Replace("/", "\\") + filename + "." + arr_filename[arr_filename.Length - 1];
count++;
} while (File.Exists(tarpath));
File.Move(oripath, tarpath);
}
//檔案移動
return otb_sys_document_bll.SingleFileMove(guid, filename, targetpath, tarpath.Replace(FileRoot, "").Replace("\\", "/"), ModifyUser);
}
catch (Exception ex)
{
BasePage.mo_Log.Error("Document SingleFileMove Error:" + ex + "\nFilePath: " + filepath + filename + "\nMoveFilePath: " + targetpath + filename);
return false;
}
}
#endregion
#region SaveMemo 即時儲存更新圖檔資訊
[WebMethod]
public bool SaveMemo(string FileId, string FilePath, string FileName, string oldFileName, string CFName, string EFName, string strNumber, string FileType, string UpdateMemo, string ModifyUser)
{
FilePath = HttpUtility.UrlDecode(FilePath, System.Text.Encoding.UTF8);
FileName = HttpUtility.UrlDecode(FileName, System.Text.Encoding.UTF8);
oldFileName = HttpUtility.UrlDecode(oldFileName, System.Text.Encoding.UTF8);
CFName = HttpUtility.UrlDecode(CFName, System.Text.Encoding.UTF8);
EFName = HttpUtility.UrlDecode(EFName, System.Text.Encoding.UTF8);
UpdateMemo = HttpUtility.UrlDecode(UpdateMemo, System.Text.Encoding.UTF8);
string oldFileRoot = ""; //原始檔案路徑,做為更換檔名的條件
string FileRoot = getFileRoot(); //儲存檔案路徑
try
{
OT.BLL.OTB_SYS_Document otb_sys_document_bll = new OT.BLL.OTB_SYS_Document();
ModifyUser = ModifyUser == "" ? "admin" : ModifyUser;
if (CFName != "" || EFName != "") //如果中文或英文不為空才移動檔案,如果都為空就更新Memo
{
if (oldFileName != FileName) //如果檔名比對不相同才更新實體檔名
{
//檔案完整路徑
oldFileRoot = FileRoot + FilePath.Replace("/", "\\") + oldFileName + FileType;
FileRoot += FilePath.Replace("/", "\\") + FileName + FileType;
File.Move(@oldFileRoot, @FileRoot);
}
}
return otb_sys_document_bll.SaveMemo(FileId, FileName, CFName, EFName, strNumber, FilePath + FileName + FileType, UpdateMemo, ModifyUser); ;
}
catch (Exception ex)
{
BasePage.mo_Log.Error("Document SaveMemo Error:" + ex + "\nFilePath: " + FileRoot);
return false;
}
}
#endregion
#region DownloadToZip 檔案下載
[WebMethod]
public bool DownloadToZip(string filepath)
{
string[] path = filepath.Split('|');
var memoryStream = new System.IO.MemoryStream();
//若遇到中文檔名,但未加System.Text.Encoding.Default,則檔案會無法AddFile
using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))
{
string fileroot = getFileRoot();
for (int count = 0; count < path.Length; count++)
{
path[count] = (fileroot + path[count]).Replace("/", "\\");
}
zip.AddFiles(@path, ""); //第二個參數設為空值表示壓縮檔案時不將檔案路徑加入
zip.Save(memoryStream);
//zip.Save(DateTime.Now.ToString("yyyy_MM_dd") + ".zip");
}
//HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("yyyy_MM_dd") + ".zip");
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray());
//HttpContext.Current.Response.End();
memoryStream.Dispose();
return true;
}
#endregion
#region SyncDir 同步資料夾
[WebMethod]
public bool SyncDir()
{
//DirectoryInfo di = new DirectoryInfo(@fileroot);
OT.Model.OTB_SYS_Document OTB_SYS_Document = new Model.OTB_SYS_Document();
OT.BLL.OTB_SYS_Document OTB_SYS_Document_BLL = new BLL.OTB_SYS_Document();
string OriginRoot = Server.MapPath(@fileroot);
string ParentRoot;
string FileRoot = getFileRoot(); //取得根目錄路徑
bool flag = true; //更新標記
if (OTB_SYS_Document_BLL.InitDirectory())
{
string Root = ((OriginRoot).Replace(FileRoot, "\\")).Replace("\\", "/");
OTB_SYS_Document.Organization = OT.Web.Ap_Code.BasePage.gstrOrganizationID;
OTB_SYS_Document.FileName = Root.Replace("/", ""); //資料夾名稱
OTB_SYS_Document.FileRoot = "/"; //父層路徑
OTB_SYS_Document.FilePath = Root; //父層路徑+本身路徑
OTB_SYS_Document.CreateUser = "apadmin";
OTB_SYS_Document_BLL.UpdateDirectoryToDB(OTB_SYS_Document);
foreach (var i in Directory.GetDirectories(OriginRoot, "*", SearchOption.AllDirectories))
{
string RemoveDirectory = GetDeleteDirectory();
DirectoryInfo di = new DirectoryInfo(@i); //取得該路徑資料夾資訊
if (di.Name != RemoveDirectory)
{
OTB_SYS_Document = new Model.OTB_SYS_Document();
ParentRoot = ((di.Parent.FullName).Replace(FileRoot, "\\")).Replace("\\", "/"); //起始加上"/"將多餘的路徑分隔符號取代成空白
OTB_SYS_Document.Organization = OT.Web.Ap_Code.BasePage.gstrOrganizationID;
OTB_SYS_Document.FileName = di.Name; //資料夾名稱
OTB_SYS_Document.FileRoot = ParentRoot + "/"; //父層路徑
OTB_SYS_Document.FilePath = ParentRoot + "/" + di.Name + "/"; //父層路徑+本身路徑
OTB_SYS_Document.CreateUser = "apadmin";
try
{
if (!OTB_SYS_Document_BLL.UpdateDirectoryToDB(OTB_SYS_Document))
{
//更新失敗變成標記狀態
flag = false;
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
}
}
//創建刪除資料夾
string DeleteDirectoryRoot = getFileRoot() + getTopDirectory() + "\\" + RemoveDirectory;
if (!Directory.Exists(DeleteDirectoryRoot))
{
Directory.CreateDirectory(DeleteDirectoryRoot); //創建刪除資料夾
}
}
if (flag)
{
//true 代表更新成功 刪除狀態為-1的資料夾
try
{
if (!OTB_SYS_Document_BLL.DeleteDirectory())
{
flag = false;
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
}
}
return flag;
}
else
{
return false;
}
}
#endregion
#region AuthCheck 檢查路徑權限
[WebMethod]
public string AuthCheck(string organization, string path, string createuser, string Group, string Dep, string SourceID)
{
OT.BLL.OTB_SYS_Document OTB_SYS_Document_BLL = new BLL.OTB_SYS_Document();
if (!string.IsNullOrEmpty(path))
{
//回傳路徑不為空
path = HttpUtility.UrlDecode(path);
}
else
{
path = fileroot.Substring(1);
}
if (!string.IsNullOrEmpty(organization) && !string.IsNullOrEmpty(createuser))
{
System.Data.DataSet ds = OTB_SYS_Document_BLL.GetFilePath(organization, path, createuser, Group, Dep, SourceID);
ds.Tables[0].TableName = "Directory";
ds.Tables[1].TableName = "File";
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
return json;
}
else
{
return "#error:{\"empty\":\"1\"}";
}
}
#endregion
#region UserRuleDepartment 查詢所有使用者
[WebMethod]
public string UserRuleDepartment(string organization)
{
System.Text.StringBuilder strSql = new System.Text.StringBuilder();
strSql.Append(" select MemberID,MemberName from OTB_SYS_Members where OrganizationID = @OrganizationID ");
strSql.Append(" select DepartmentID, DepartmentShortName from OTB_SYS_Departments where OrganizationID = @OrganizationID ");
strSql.Append(" select RuleID,RuleName from OTB_SYS_Rules where OrganizationID = @OrganizationID ");
SqlParameter[] parameters = {
new SqlParameter("@OrganizationID", SqlDbType.NVarChar,50)
};
parameters[0].Value = organization;
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
ds.Tables[0].TableName = "User";
ds.Tables[1].TableName = "Dep";
ds.Tables[2].TableName = "Group";
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
if (!string.IsNullOrEmpty(json))
{
return json;
}
else
{
return "";
}
}
#endregion
#region UpdateUserRule 更新使用者權限
[WebMethod]
public string UpdateUserRule(string organization, string RUID, string FUID, string FileType, string RuleUser, string RuleGroup, string RuleDep, string Rule, string UnRule, string User)
{
try
{
if (!string.IsNullOrEmpty(Rule) || !string.IsNullOrEmpty(UnRule))
{
if (string.IsNullOrEmpty(RUID))
{
//RUID為空新增一筆權限
RUID = Guid.NewGuid().ToString();
}
System.Text.StringBuilder strSql = new System.Text.StringBuilder();
strSql.Append(" declare @RowCount int ");
strSql.Append(" select @RowCount = COUNT(0) from OTB_SYS_DocumentRule ");
strSql.Append(" where OrganizationID = @OrganizationID ");
strSql.Append(" and [FUID] = @FUID ");
strSql.Append(" and (ISNULL([USER],'') = @RuleUser) ");
strSql.Append(" and (ISNULL([Group],'') = @RuleGroup) ");
strSql.Append(" and (ISNULL([Department],'') = @RuleDep) ");
strSql.Append(" if @RowCount > 0 ");
strSql.Append(" begin ");
strSql.Append(" update OTB_SYS_DocumentRule ");
strSql.Append(" set ");
strSql.Append(" FileType = @FileType ");
strSql.Append(" , [User] = isnull(@RuleUser,'') ");
strSql.Append(" , [Group] = isnull(@RuleGroup,'') ");
strSql.Append(" , [Department] = isnull(@RuleDep,'') ");
strSql.Append(" , [Rule] = isnull(@Rule,'') ");
strSql.Append(" , [UnRule] = isnull(@UnRule,'') ");
strSql.Append(" , ModifyUser = @User ");
strSql.Append(" , ModifyDate = GETDATE() ");
strSql.Append(" where OrganizationID = @OrganizationID ");
strSql.Append(" and [FUID] = @FUID ");
strSql.Append(" and (ISNULL([USER],'') = @RuleUser) ");
strSql.Append(" and (ISNULL([Group],'') = @RuleGroup) ");
strSql.Append(" and (ISNULL([Department],'') = @RuleDep) ");
strSql.Append(" end ");
strSql.Append(" else ");
strSql.Append(" begin ");
strSql.Append(" insert into OTB_SYS_DocumentRule(OrganizationID,RUID,FUID,FileType,[User],[Group],[Department],[Rule],[UnRule],CreateUser,CreateDate) ");
strSql.Append(" values(@OrganizationID,@RUID,@FUID,@FileType,isnull(@RuleUser,''),isnull(@RuleGroup,'admin'),isnull(@RuleDep,''),isnull(@Rule,''),isnull(@UnRule,''),@User,GETDATE()) ");
strSql.Append(" end ");
SqlParameter[] parameters = {
new SqlParameter("@OrganizationID", SqlDbType.NVarChar,50),
new SqlParameter("@RUID", SqlDbType.Char,36),
new SqlParameter("@FUID", SqlDbType.Char,36),
new SqlParameter("@FileType", SqlDbType.NVarChar,20),
new SqlParameter("@RuleUser", SqlDbType.NVarChar,100),
new SqlParameter("@RuleGroup", SqlDbType.NVarChar,100),
new SqlParameter("@RuleDep", SqlDbType.NVarChar,100),
new SqlParameter("@Rule", SqlDbType.NVarChar,100),
new SqlParameter("@UnRule", SqlDbType.NVarChar,100),
new SqlParameter("@User", SqlDbType.NVarChar,50)
};
parameters[0].Value = organization;
parameters[1].Value = RUID;
parameters[2].Value = FUID;
parameters[3].Value = FileType;
parameters[4].Value = RuleUser;
parameters[5].Value = RuleGroup;
parameters[6].Value = RuleDep;
parameters[7].Value = Rule;
parameters[8].Value = UnRule;
parameters[9].Value = User;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return "1";
}
else
{
return "";
}
}
else
{
return "0";
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region getAuthContent 取得不同類別使用者內容
[WebMethod]
public string getAuthContent(string organization, string FUID)
{
try
{
System.Text.StringBuilder strSql = new System.Text.StringBuilder();
strSql.Append(" select [RUID],[FUID],FileType,[USER],[GROUP],[Department] ");
strSql.Append(" ,case ");
strSql.Append(" when ISNULL(m.MemberName,'') <> '' then m.MemberName ");
strSql.Append(" when ISNULL(r.RuleName,'') <> '' then r.RuleName ");
strSql.Append(" when ISNULL(d.DepartmentShortName,'') <> '' then d.DepartmentShortName ");
strSql.Append(" end as Cname ");
strSql.Append(" ,[Rule],[UnRule],dr.CreateUser from OTB_SYS_DocumentRule dr ");
strSql.Append(" left join (select MemberID,MemberName from OTB_SYS_Members where OrganizationID = 'Origtek') m ");
strSql.Append(" on dr.[User] = m.MemberID ");
strSql.Append(" left join (select RuleID,RuleName from OTB_SYS_Rules where OrganizationID = 'Origtek') r ");
strSql.Append(" on dr.[Group] = r.RuleID ");
strSql.Append(" left join (select DepartmentID, DepartmentShortName from OTB_SYS_Departments where OrganizationID = 'Origtek') d ");
strSql.Append(" on dr.[Department] = d.DepartmentID ");
strSql.Append(" where dr.OrganizationID = @OrganizationID and dr.[FUID] = @FUID ");
SqlParameter[] parameters = {
new SqlParameter("@OrganizationID", SqlDbType.NVarChar,50),
new SqlParameter("@FUID", SqlDbType.Char,36)
};
parameters[0].Value = organization;
parameters[1].Value = FUID;
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
if (!string.IsNullOrEmpty(json))
{
return json;
}
else
{
return "";
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region CheckFileAuth 檢查儲存前的權限
[WebMethod]
public string CheckFileAuth(string Organization, string FUID, string User, string Group, string Dep)
{
try
{
System.Text.StringBuilder strSql = new System.Text.StringBuilder();
strSql.Append(" select top 1 [FUID], [Rule] from OTB_SYS_DocumentRule ");
strSql.Append(" where OrganizationID = @OrganizationID ");
strSql.Append(" and [FUID] = @FUID ");
strSql.Append(" and (([USER] = @User AND @User <> '') ");
strSql.Append(" or ([Group] in (select RuleID from OTB_SYS_MembersToRule where MemberID = @User) AND @User <> '') ");
strSql.Append(" or ([Department] = @Dep AND @Dep <> '') ) ");
strSql.Append(" order by [USER] desc ,[Group] desc,[Department] desc ");
SqlParameter[] parameters = {
new SqlParameter("@OrganizationID", SqlDbType.NVarChar,50),
new SqlParameter("@FUID", SqlDbType.Char,36),
new SqlParameter("@User", SqlDbType.NVarChar,100),
new SqlParameter("@Group", SqlDbType.NVarChar,100),
new SqlParameter("@Dep", SqlDbType.NVarChar,100),
new SqlParameter("@CmdText", SqlDbType.Char,1)
};
parameters[0].Value = Organization;
parameters[1].Value = FUID;
parameters[2].Value = User;
parameters[3].Value = Group;
parameters[4].Value = Dep;
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
ds.Tables[0].TableName = "info";
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
if (!string.IsNullOrEmpty(json))
{
return json;
}
else
{
return "";
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region ReadCurrFile 讀取現有DB檔案
[WebMethod]
public string ReadCurrFile()
{
//儲存檔案路徑
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" select [GUID],[FilePath] from OTB_SYS_Document where [FileType] = 'File' and Isnull([status],0) <> 99");
DataSet ds = DbHelperSQL.Query(strSql.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
string json = JsonConvert.SerializeObject(ds, Formatting.Indented);
return json;
}
else
{
return "";
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region CheckUpdateFileExists 檢查更新檔案是否存在
[WebMethod]
public string CheckUpdateFileExists()
{
string FileRoot = getFileRoot();
//儲存檔案路徑
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" select [GUID],[FilePath] from OTB_SYS_Document where [FileType] = 'File' and IsDelete <> 'Y' and Isnull([status],0) <> 99");
DataSet ds = DbHelperSQL.Query(strSql.ToString());
DataTable tb = ds.Tables[0].Clone(); //儲存不存在檔案的列表
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string FilePath = ""; //檔案路徑
string FileFullPath; //檔案完整路徑
if (dr["FilePath"].ToString().Substring(0) == "/")
{
FilePath = dr["FilePath"].ToString().Substring(0);
}
else
{
FilePath = dr["FilePath"].ToString();
}
FileFullPath = FileRoot + FilePath;
if (!System.IO.File.Exists(@FileFullPath))
{
//不存在
tb.ImportRow(dr);
}
}
}
return JsonConvert.SerializeObject(tb, Formatting.Indented);
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region UpdateNotExistsFile 更新不存在的檔案
[WebMethod]
public string UpdateNotExistsFile()
{
string FileRoot = getFileRoot();
//儲存檔案路徑
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" select [GUID],[FilePath] from OTB_SYS_Document where Isnull([status],0) <> 99");
DataSet ds = DbHelperSQL.Query(strSql.ToString());
//DataTable tb = ds.Tables[0].Clone(); //儲存不存在檔案的列表
DataTable tb = new DataTable();
DataColumn col;
col = new DataColumn();
col.ColumnName = "GUID";
tb.Columns.Add(col);
col = new DataColumn();
col.ColumnName = "FilePath";
tb.Columns.Add(col);
col = new DataColumn();
col.ColumnName = "exception";
tb.Columns.Add(col);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string FilePath = ""; //檔案路徑
string FileFullPath; //檔案完整路徑
if (dr["FilePath"].ToString().Substring(0) == "/")
{
FilePath = dr["FilePath"].ToString().Substring(0);
}
else
{
FilePath = dr["FilePath"].ToString();
}
FileFullPath = FileRoot + FilePath;
if (!System.IO.File.Exists(@FileFullPath))
{
//不存在
StringBuilder NewStrSql = new StringBuilder();
NewStrSql.Append(" update OTB_SYS_Document ");
NewStrSql.Append(" set [status] = 99 ");
NewStrSql.Append(" where [GUID] = '" + dr["GUID"] + "'");
try
{
int rows = DbHelperSQL.ExecuteSql(NewStrSql.ToString());
if (rows <= 0)
{
DataRow NewDr = tb.NewRow();
NewDr["GUID"] = dr["GUID"];
NewDr["FilePath"] = dr["FilePath"];
NewDr["exception"] = "更新失敗,資料庫找不到資料";
}
}
catch (Exception ex)
{
//例外
//tb.ImportRow(dr);
DataRow NewDr = tb.NewRow();
NewDr["GUID"] = dr["GUID"];
NewDr["FilePath"] = dr["FilePath"];
NewDr["exception"] = ex.Message;
}
}
}
}
return JsonConvert.SerializeObject(tb, Formatting.Indented);
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region GetFileAllDirectory 取得現有資料夾
[WebMethod]
public string GetFileAllDirectory()
{
string FileRoot = getFileRoot();
string TopRoot = getTopDirectory();
//儲存檔案路徑
try
{
string FullPath = FileRoot + TopRoot;
DataTable tb = new DataTable();
DataColumn col;
col = new DataColumn();
col.ColumnName = "DirectoryName";
tb.Columns.Add(col);
//col = new DataColumn();
//col.ColumnName = "DirectoryPath";
//tb.Columns.Add(col);
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@FullPath);
string DeleteDirectory = GetDeleteDirectory();
foreach (System.IO.DirectoryInfo di_child in di.GetDirectories().OrderBy(p => p.Name))
{
//讀取資料夾名稱
if (DeleteDirectory != di_child.Name)
{
DataRow NewDr;
NewDr = tb.NewRow();
NewDr["DirectoryName"] = di_child.Name;
tb.Rows.Add(NewDr);
//NewDr = tb.NewRow();
//NewDr["DirectoryPath"] = di_child.Name;
}
}
return JsonConvert.SerializeObject(tb, Formatting.Indented);
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region UpdateFileAllDirectory 更新資料夾內的檔案
[WebMethod]
public string UpdateFileAllDirectory(string DirectoryName)
{
string FileRoot = getFileRoot();
string TopRoot = getTopDirectory();
//儲存檔案路徑
try
{
//成功資料表
DataTable tb = new DataTable();
DataColumn col;
col = new DataColumn();
col.ColumnName = "GUID";
tb.Columns.Add(col);
col = new DataColumn();
col.ColumnName = "FilePath";
tb.Columns.Add(col);
//失敗資料表
DataTable tb_fail = new DataTable();
DataColumn col_fail;
col_fail = new DataColumn();
col_fail.ColumnName = "GUID";
tb_fail.Columns.Add(col_fail);
col_fail = new DataColumn();
col_fail.ColumnName = "FilePath";
tb_fail.Columns.Add(col_fail);
col_fail = new DataColumn();
col_fail.ColumnName = "Exception";
tb_fail.Columns.Add(col_fail);
if (!string.IsNullOrEmpty(DirectoryName))
{
string FullPath = FileRoot + TopRoot + "\\" + DirectoryName;
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@FullPath);
foreach (System.IO.FileInfo fi in di.GetFiles("*", SearchOption.AllDirectories).OrderBy(o => o.FullName))
{
string FileExtend = GetFileExtend().ToLower();
//if (("|.jpg|.jpeg|.png|.gif|").Contains("|" + fi.Extension.ToLower() + "|"))
if (FileExtend.IndexOf(fi.Extension.ToLower().Substring(1)) > -1)
{
if (File.Exists(fi.FullName) && fi.Length > 0)
{
StringBuilder CheckSql = new StringBuilder();
string NewFilePath = fi.FullName.Replace(FileRoot, "/").Replace("\\", "/");
CheckSql.Append(" select [FilePath] from OTB_SYS_Document ");
CheckSql.Append(" where [FilePath] = @FilePath ");
SqlParameter[] para = {
new SqlParameter("@FilePath", SqlDbType.NVarChar,500)
};
para[0].Value = NewFilePath;
DataSet dsCount = DbHelperSQL.Query(CheckSql.ToString(), para);
if (dsCount.Tables[0].Rows.Count <= 0)
{
string New_GuId = Guid.NewGuid().ToString();
try
{
string strOrganize = "";
try
{
strOrganize = OT.Web.Ap_Code.BasePage.gstrOrganizationID;
}
catch (Exception ex)
{
strOrganize = "";
}
string stringToBase64 = "";
OT.Model.OTB_SYS_Document otb_sys_document_model = new OT.Model.OTB_SYS_Document();
OT.BLL.OTB_SYS_Document otb_sys_document_bll = new OT.BLL.OTB_SYS_Document();
//沒找到才新增
otb_sys_document_model.Organization = strOrganize;
otb_sys_document_model.GUID = New_GuId; //GUID
otb_sys_document_model.FileName = Path.GetFileNameWithoutExtension(fi.Name); //檔案名稱
otb_sys_document_model.SubFileName = Path.GetExtension(fi.Name); //檔案副檔名
otb_sys_document_model.FileRoot = NewFilePath.Replace(fi.Name, ""); //檔案路徑
otb_sys_document_model.FilePath = NewFilePath; //檔案完整路徑
otb_sys_document_model.FileSize = Convert.ToInt32(fi.Length / 1024); //檔案大小(KB)
if (isImage(fi.Extension))
{
using (var ms = new MemoryStream())
{
using (var fs = new FileStream(fi.FullName, FileMode.Open))
{
using (var img = System.Drawing.Image.FromStream(fs))
{
int intW = 100;
int intH = 100;
if (img.Width > img.Height)
{
intW = 100;
intH = (int)100 * img.Height / img.Width;
}
else
{
intH = 100;
intW = (int)100 * img.Width / img.Height;
}
otb_sys_document_model.PixelW = img.Width.ToString();
otb_sys_document_model.PixelH = img.Height.ToString();
using (var NewImage = new System.Drawing.Bitmap(intW, intH))
{
using (var g = System.Drawing.Graphics.FromImage(NewImage))
{
g.DrawImage(img, 0, 0, intW, intH);
NewImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
stringToBase64 = Convert.ToBase64String(imageBytes);
}
}
}
}
}
otb_sys_document_model.FileContent = "data:image/jpeg;base64," + stringToBase64;
}
else
{
otb_sys_document_model.PixelW = "0";
otb_sys_document_model.PixelH = "0";
otb_sys_document_model.FileContent = "";
}
otb_sys_document_model.IsProtected = "N"; //是否能複製、移除
otb_sys_document_model.IsPublic = "N"; //是否共用
otb_sys_document_model.Memo = NewFilePath.Replace("/", " "); //關鍵字查詢
otb_sys_document_model.FileCreateDate = fi.CreationTime.ToString("yyyy/MM/dd hh:mm:s"); //檔案創建日
otb_sys_document_model.CreateUser = "apadmin"; //創建人
otb_sys_document_model.ModifyUser = "apadmin"; //修改人
if (otb_sys_document_bll.Add(otb_sys_document_model))
{
DataRow NewDr = tb.NewRow();
NewDr["GUID"] = New_GuId;
NewDr["FilePath"] = NewFilePath;
tb.Rows.Add(NewDr);
}
else
{
DataRow NewDr = tb_fail.NewRow();
NewDr["GUID"] = New_GuId;
NewDr["FilePath"] = NewFilePath;
NewDr["Exception"] = "資料庫新增失敗";
tb_fail.Rows.Add(NewDr);
}
}
catch (Exception ex)
{
DataRow NewDr = tb_fail.NewRow();
NewDr["GUID"] = New_GuId;
NewDr["FilePath"] = NewFilePath;
NewDr["Exception"] = ex.Message;
tb_fail.Rows.Add(NewDr);
}
}
}
}
}
}
DataSet ds = new DataSet();
ds.Tables.Add(tb);
ds.Tables.Add(tb_fail);
ds.Tables[0].TableName = "complete";
ds.Tables[1].TableName = "fail";
return JsonConvert.SerializeObject(ds, Formatting.Indented);
}
catch (Exception ex)
{
BasePage.mo_Log.Error(ex.Message, ex);
return "";
}
}
#endregion
#region GetFileExtend 取得文管允許檔案類型
public string GetFileExtend()
{
string DefaultFileExtend = "jpg|jpeg|gif|png";
string FileExtend;
FileExtend = DefaultFileExtend;
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" select SettingValue from OTB_SYS_SystemSetting ");
strSql.Append(" where SettingItem = 'FileExtend' ");
DataSet ds = DbHelperSQL.Query(strSql.ToString());
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
if (!string.IsNullOrEmpty(ds.Tables[0].Rows[0][0].ToString()))
{
FileExtend = ds.Tables[0].Rows[0][0].ToString();
}
}
}
}
catch (Exception ex)
{
BasePage.mo_Log.Error("GetFileExtend Error:" + ex.Message);
}
return FileExtend;
}
#endregion
#region isImage 檢查是否為圖檔
public bool isImage(string subFileName)
{
subFileName = subFileName.ToLower();
List<string> imageExtend = new List<string> { ".jpg", ".jpeg", ".tiff", ".gif", ".bmp", ".png", ".rif" };
return imageExtend.Any(img => !img.Except(subFileName).Any());
}
#endregion
#region GetCurrentFileExtend WS取得目前允許上傳檔案類型
[WebMethod]
public string GetCurrentFileExtend()
{
return GetFileExtend().ToLower();
}
#endregion
#region DeleteFile 檔案移除
[WebMethod]
public string DeleteFile(string id)
{
DataTable tb = new DataTable();
DataColumn col;
col = new DataColumn();
col.ColumnName = "GUID";
tb.Columns.Add(col);
col = new DataColumn();
col.ColumnName = "NAME";
tb.Columns.Add(col);
col = new DataColumn();
col.ColumnName = "TYPE";
tb.Columns.Add(col);
col = new DataColumn();
col.ColumnName = "DONE";
tb.Columns.Add(col);
JArray JsonId = (JArray)JsonConvert.DeserializeObject(id);
string root = getFileRoot();
string DeleteDirectory = root + getTopDirectory() + "\\" + GetDeleteDirectory(); //取得目前刪除資料夾路徑位置
foreach (JObject ObjId in JsonId)
{
string eachId = ObjId["id"].ToString(); //檔案或資料夾的ID
string DeleteGUID = Guid.NewGuid().ToString().ToUpper(); //當刪除時產生GUID,用於還原時辨識
StringBuilder strSql = new StringBuilder();
//更新相關資料夾 Start
strSql.Append(" declare @FilePath nvarchar(1000) ");
strSql.Append(" select @FilePath = FilePath + '%' from OTB_SYS_Document where IsDelete = 'N' AND [GUID] = @id");
strSql.Append(" update OTB_SYS_Document set [status] = 99 where [GUID] = @id ");
strSql.Append(" update OTB_SYS_Document set IsDelete = 'Y',DeleteID = @DeleteID where FileRoot like @FilePath and ISNULL(DeleteID, '') = '' or [GUID] = @id ");
//更新相關資料夾 End
strSql.Append(" select * from OTB_SYS_Document where [GUID] = @id ");
SqlParameter[] parameters = {
new SqlParameter("@id", SqlDbType.Char,36),
new SqlParameter("@DeleteID", SqlDbType.Char,36)
};
parameters[0].Value = eachId;
parameters[1].Value = DeleteGUID;
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
if (ds.Tables.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
try
{
string NewFileRoot = DeleteDirectory + "\\" + eachId; //GUID名稱的資料夾路徑
string MoveFileRoot = root + dr["FilePath"]; //要移動的資料夾或檔案路徑
MoveFileRoot = MoveFileRoot.Replace("/", "\\");
DirectoryInfo di = new DirectoryInfo(@NewFileRoot);
if (!Directory.Exists(@NewFileRoot)) //檢查資料夾是否存在
{
di.Create();
}
if (dr["FileType"].ToString().ToLower() == "directory")
{
//資料夾移動
Directory.Move(@MoveFileRoot, NewFileRoot + "\\" + dr["FileName"]);
}
else
{
File.Move(@MoveFileRoot, @NewFileRoot + "\\" + Path.GetFileName(@MoveFileRoot));
}
DataRow NewDr = tb.NewRow();
NewDr["GUID"] = eachId;
NewDr["NAME"] = dr["FileName"];
NewDr["TYPE"] = dr["FileType"];
NewDr["DONE"] = "1";
tb.Rows.Add(NewDr);
}
catch (Exception ex)
{
DataRow NewDr = tb.NewRow();
NewDr["GUID"] = eachId;
NewDr["NAME"] = dr["FileName"];
NewDr["TYPE"] = dr["FileType"];
NewDr["DONE"] = "0";
tb.Rows.Add(NewDr);
//還原
StringBuilder OstrSql = new StringBuilder();
strSql.Append(" update OTB_SYS_Document set [status] = 1 where [GUID] = @id ");
OstrSql.Append(" update OTB_SYS_Document set IsDelete = 'N' where DeleteID = @DeleteID ");
SqlParameter[] para = {
new SqlParameter("@id", SqlDbType.Char,36),
new SqlParameter("@DeleteID", SqlDbType.Char,36)
};
parameters[0].Value = eachId;
parameters[1].Value = DeleteGUID;
DbHelperSQL.ExecuteSql(OstrSql.ToString(), para);
}
}
}
}
return JsonConvert.SerializeObject(tb, Newtonsoft.Json.Formatting.Indented); ;
}
#endregion
#region GetTrashDocumentFile 回收桶,取得被移除的檔案
[WebMethod]
public string GetTrashDocumentFile()
{
string return_element = "";
string ele_file = "";
string ele_file_ul = "<ul class='jqueryFileTree'>[file_li]</ul>";
string ele_file_li = "\t<li filetype=\"[filetype]\" mime=\"[mime]\" class=\"file ext_img\"><a fid=\"[guid]\" style=\"width:[maxW]px;height:[maxH]px\" href=\"#\"><p><img id='[guid]' class='[class]' oldstyle=\"1px solid [borderColor]\" title=\"[filename_sub]\n原圖大小:[imgwidth] x [imgheight]\" imgW=\"[imgwidth]\" imgH=\"[imgheight]\" imgSize=\"[imgSize]\" keyword=\"[keyword]\" filename=\"[filename]\" cfname=\"[cfname]\" efname=\"[efname]\" filetype=\"[type]\" fileroot=\"[fileroot]\" alt='' realSrc=\"[filepath]\" src=\"[base64string]\" /></p></a><span style='width:100%; text-overflow:ellipsis; display:inline-block; overflow:hidden;'>[filename]</span></li>\n";
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" select [GUID], PUID, [FileName], CFName, EFName, FileNumber, isnull(SubFileName,'') as SubFileName, FileRoot, FilePath, isnull(FileSize,0) as FileSize, isnull(PixelW,0) as PixelW, isnull(PixelH,0) as PixelH, isnull(FileContent,'') as FileContent, IsProtected, IsPublic, IsDelete, isnull(Memo,'') as Memo, FileCreateDate, FileType, CreateUser, CreateDate, ModifyUser, ModifyDate, status, isnull(DeleteID,'') as DeleteID from OTB_SYS_Document where IsDelete = 'Y' and [status] = 99 ");
DataSet ds = DbHelperSQL.Query(strSql.ToString());
foreach (DataRow dr in ds.Tables[0].Rows)
{
string borderColor = "#FFF";
int maxW = 100, maxH = 100; //縮圖最大寬度與高度
string base64String = dr["FileContent"].ToString().Replace(",", "&#44;");
int ImgWidth = Convert.ToInt16(dr["PixelW"]);
int ImgHeight = Convert.ToInt16(dr["PixelH"]);
string strClass = ""; //取得要顯示的類型
if (dr["FileType"].ToString().ToLower() == "directory")
{
strClass = "directory";
}
else if (string.IsNullOrEmpty(base64String))
{
strClass = dr["SubFileName"].ToString().Substring(1);
}
ele_file += ele_file_li.Replace("[filetype]", !string.IsNullOrEmpty(dr["SubFileName"].ToString()) ? dr["SubFileName"].ToString().Substring(1) : dr["SubFileName"].ToString()).Replace("[mime]", string.IsNullOrEmpty(base64String) ? "application" : "image").Replace("[borderColor]", borderColor).Replace("[maxW]", maxW.ToString()).Replace("[maxH]", maxH.ToString()).Replace("[guid]", dr["GUID"].ToString()).Replace("[class]", strClass).Replace("[filename_sub]", dr["FileName"].ToString() + dr["SubFileName"].ToString()).Replace("[imgwidth]", ImgWidth.ToString()).Replace("[imgheight]", ImgHeight.ToString()).Replace("[imgSize]", dr["FileSize"].ToString()).Replace("[cfname]", dr["CFName"].ToString()).Replace("[efname]", dr["EFName"].ToString()).Replace("[keyword]", dr["Memo"].ToString()).Replace("[type]", dr["SubFileName"].ToString()).Replace("[fileroot]", dr["FileRoot"].ToString()).Replace("[filepath]", dr["FilePath"].ToString()).Replace("[base64string]", base64String).Replace("[filename]", dr["FileName"].ToString());
}
return_element = ele_file_ul.Replace("[file_li]", ele_file);
}
catch (Exception ex)
{
}
return return_element;
}
#endregion
[WebMethod]
#region ReCoverDocument 還原被刪除的檔案
public bool ReCoverDocument(string GUID)
{
bool success = false;
string root = getFileRoot(); //取得檔案根目錄
string DeleteDirectory = root + getTopDirectory() + "\\" + GetDeleteDirectory(); //取得目前刪除資料夾路徑位置
string[] IDList = GUID.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string strID in IDList)
{
try
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" select * from OTB_SYS_Document where [GUID] = @GUID ");
SqlParameter[] parameters = {
new SqlParameter("@GUID", SqlDbType.Char,36)};
parameters[0].Value = strID;
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
DataRow dr = ds.Tables[0].Rows[0];
string DeleteID = dr["DeleteID"].ToString(); //刪除的ID
string FileType = dr["FileType"].ToString().ToLower(); //檔案類型
string FileRoot = dr["FileRoot"].ToString(); //檔案根目錄
string FilePath = dr["FilePath"].ToString(); //檔案路徑
string FileName = dr["FileName"].ToString(); //檔案名稱
string subFileName = dr["SubFileName"].ToString(); //檔案副檔名
if (FileType == "file")
{
string curr_file_path = root + FileRoot.Replace("/", "\\") + FileName + subFileName; //完整路徑名稱
string oldFileName = FileName; //紀錄原始檔案名稱
int count = 0;
while (File.Exists(@curr_file_path))
{
FileName = oldFileName + "_" + count.ToString();
curr_file_path = root + FileRoot.Replace("/", "\\") + FileName + subFileName;
count++;
}
}
else
{
string curr_file_path = root + FileRoot.Replace("/", "\\") + FileName; //完整路徑名稱
string oldFileName = FileName; //紀錄原始檔案名稱
int count = 0;
bool needMove = false;
while (Directory.Exists(@curr_file_path))
{
needMove = true;
FileName = oldFileName + "_" + count.ToString();
curr_file_path = root + FileRoot.Replace("/", "\\") + FileName;
count++;
}
strSql = new StringBuilder();
//復原資料夾狀態
strSql.Append(" update OTB_SYS_Document set IsDelete = 'N',[status] = 1,[DeleteID] = '' where [DeleteID] = @DeleteID ");
//更新資料夾名稱
strSql.Append(" update OTB_SYS_Document set [FileName] = @FileName,[FilePath] = @NewFilePath where [GUID] = @GUID ");
//更新資料夾下的相關路徑
strSql.Append(" ;with F([GUID]) ");
strSql.Append(" as ");
strSql.Append(" ( ");
strSql.Append(" select [GUID] from OTB_SYS_Document ");
strSql.Append(" where [GUID] = @GUID ");
strSql.Append(" union all ");
strSql.Append(" select parent.[GUID] from OTB_SYS_Document as parent ");
strSql.Append(" inner join F as main ");
strSql.Append(" on main.[GUID] = parent.[PUID] ");
strSql.Append(" ) ");
strSql.Append(" update OTB_SYS_Document ");
strSql.Append(" set [FileRoot] = replace([FileRoot],@OldFilePath,@NewFilePath) ");
strSql.Append(" , [FilePath] = replace([FilePath],@OldFilePath,@NewFilePath) ");
strSql.Append(" where [GUID] in (select [GUID] from F) and [FileRoot] like @FileRoot and [GUID] <> @GUID ");
SqlParameter[] param = {
new SqlParameter("@GUID", SqlDbType.Char,36),
new SqlParameter("@DeleteID", SqlDbType.Char,36),
new SqlParameter("@NewFilePath", SqlDbType.NVarChar,500),
new SqlParameter("@FileName", SqlDbType.NVarChar,200),
new SqlParameter("@FileRoot", SqlDbType.NVarChar,200),
new SqlParameter("@OldFilePath", SqlDbType.NVarChar,200)
};
param[0].Value = strID;
param[1].Value = DeleteID;
param[2].Value = FileRoot + FileName + "/";
param[3].Value = FileName;
param[4].Value = FileRoot + "%";
param[5].Value = FilePath;
DbHelperSQL.ExecuteSql(strSql.ToString(), param);
string currFilePath = DeleteDirectory + "\\" + strID + "\\" + oldFileName;
string newFilePath = DeleteDirectory + "\\" + strID + "\\" + FileName;
/*移動實體檔案*/
if (needMove)
{ //更新資料夾名稱
Directory.Move(@currFilePath, @newFilePath);
}
Directory.Move(@currFilePath, root + FileRoot.Replace("/", "\\") + FileName);
Directory.Delete(DeleteDirectory + "\\" + strID);
success = true;
}
}
}
catch (Exception ex)
{
}
}
return success;
}
#endregion
}
}