| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 |
- using BizCom;
- using ICSharpCode.SharpZipLib.Zip;
- using NPOI.OpenXmlFormats.Shared;
- using SiteCore.Redis;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Text;
- using System.Web;
- using System.Web.UI;
- public partial class download : System.Web.UI.Page
- {
- public static string upPath = ConfigurationManager.AppSettings["upPath"];
- public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
- public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
- private void conErc(string msg)
- {
- if (msg.IndexOf("访问远程主机") == -1)
- {
- XLog.SaveLog(0, msg);
- }
- Response.Write(msg);
- //Response.End();
- }
- private void conSuc(string msg)
- {
- Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
- //Response.End();
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- Response.Buffer = true;
- downloadMore();
- }
- }
- private string getCanDownFile(string fileName)
- {
- string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
- foreach (string ext in extArr)
- {
- string fname = fileName + ext;
- if (File.Exists(fname))
- {
- return fname;
- }
- }
- return "";
- }
- private void updateIsDownSuccess(int userId, string ctid)
- {
- try
- {
- SqlParameter[] sqlParameter ={
- new SqlParameter("@mainctids", SqlDbType.VarChar,500),
- new SqlParameter("@userid", SqlDbType.VarChar,4),
- new SqlParameter("@res", SqlDbType.VarChar, 4000)
- };
- sqlParameter[0].Value = ctid;
- sqlParameter[1].Value = userId;
- sqlParameter[2].Direction = ParameterDirection.Output;
- CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
- CeErpTradeCell.UpdateRelationOrder(ctid);
- }
- catch (Exception ex)
- {
- //errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
- XLog.SaveLog(0, "下载发生错误,ctid:" + ctid + "," + ex.Message);
- }
- }
- private void downloadMore()
- {
- if (Request["hexdata"] == null || Request["hexdata"].Trim() == "")
- {
- conErc("错误的下载访问");
- return;
- }
- string tids = Request["hexdata"];
- int onlyDownFile = 0;//只下文件
- if (Request["onlyfile"] != null)
- {
- Int32.TryParse(Request["onlyfile"], out onlyDownFile);
- }
- int userId = 0;
- if (Request["userid"] != null)
- {
- Int32.TryParse(Request["userid"], out userId);
- }
- int mvClientDown = 0;//转移到客户端下载
- int isFromClient = 0;
- if (onlyDownFile != 1)
- {
- if (Request["supplier"] == null || Request["supplier"].ToString() != "1")//如果不是只下文件,那他就要是供应商
- {
- conErc("错误的下载访问");
- return;
- }
- else
- {
- Int32.TryParse(Request["isFromClient"], out isFromClient);
- if (userId > 0 && isFromClient != 1)
- {
- string file_client_down_flg = erpRedis.RedisHelper.StringGet("file_client_down_flg_" + userId);
- if (file_client_down_flg != null && file_client_down_flg == "1")
- {
- mvClientDown = 1;
- }
- }
- }
- }
- try
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5 from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1 || isFromClient == 1) ? "" : " and OrderState=5 "));
- DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
- if (dt == null || dt.Rows.Count < 1)
- {
- conErc("没有找到相关订单");
- return;
- }
- string fileMd5 = "", fileNames = "";
- List<string> files = new List<string>();
- List<string> noFileLst = new List<string>();
- List<string> ctidLst = new List<string>();
- foreach (DataRow dr in dt.Rows)
- {
- string finishDesignTime = "";
- DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
- DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
- if (ftime.CompareTo(splitTime) > 0)
- {
- finishDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
- }
- else
- {
- finishDesignTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
- }
- string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
- string fname = getCanDownFile(df_name);
- if (string.IsNullOrEmpty(fname))
- {
- noFileLst.Add("'" + dr["ctid"].ToString() + "'");
- continue;
- }
- files.Add(fname);
- ctidLst.Add(dr["ctid"].ToString());
- fileMd5 += "," + dr["FileMd5"].ToString();
- fileNames += "#$#" + Path.GetFileName(fname);
- if (onlyDownFile != 1 && mvClientDown != 1)
- copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
- }
- if (files.Count == 0)
- {
- conErc("没有找到相关的设计附件");
- return;
- }
- if (noFileLst.Count > 0)
- {
- string tips = "";
- string notids = string.Join(",", noFileLst.ToArray());
- sql = new StringBuilder();
- sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", notids, (int)OrderState.下单完成, 0, "找不到设计文件");
- CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- tips += "找不到文件,单号:" + notids;
- conErc(tips);
- return;
- }
- if (mvClientDown == 1)
- {
- for (int i = 0; i < files.Count; i++)
- {
- if (onlyDownFile != 1)
- updateIsDownSuccess(userId, ctidLst[i]);
- }
- string key = "file_client_down_list_" + userId;
- string data = "{\"hexdata\":\"" + tids + "\",\"fileMd5\":\"" + fileMd5.Substring(1) + "\",\"supplier\":\""
- + (Request["supplier"] != null ? Request["supplier"].ToString() : "0") + "\",\"fileName\":\"" + System.Web.HttpUtility.UrlEncode(fileNames, System.Text.Encoding.GetEncoding("GB2312")) + "\"}";
- erpRedis.RedisHelper.ListLeftPush(key, data);
- return;
- }
- if (files.Count == 1)
- {
- downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient);
- }
- else
- {
- ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient); //downLoadFile(userId, ctidLst[i], files[i]);
- }
- //conSuc("文件已下载完成");
- return;
- }
- catch (Exception ex)
- {
- conErc("错误的下载访问" + ex.Message);
- return;
- }
- }
- private string formatMemo(object memo)
- {
- string m = memo.ToString();
- m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
- return m;
- }
- private void copyFile(string date, string supplier, string file)
- {
- string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
- if (!Directory.Exists(path)) Directory.CreateDirectory(path);
- string fname = Path.GetFileName(file);
- File.Copy(file, path + "\\" + fname, true);
- if (!File.Exists(path + "\\" + fname))
- {
- File.Copy(file, path + "\\" + fname, true);
- }
- }
- private string getDesignTime(object v)
- {
- if (v.ToString() == "") return "";
- return Convert.ToDateTime(v).ToString("yyyyMM");
- }
- private string getDesignTimeWithDay(object v)
- {
- if (v.ToString() == "") return "";
- return Convert.ToDateTime(v).ToString("yyyyMMdd");
- }
- private string getDesignDate(object v)
- {
- return DateTime.Now.ToString("yyyy-MM-dd");
- /*if (v.ToString() == "") return "";
- return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
- }
- /// 批量进行多个文件压缩到一个文件
- /// </summary>
- /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
- /// <param name="zipFileName">生成的zip文件名称</param>
- private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
- {
- MemoryStream ms = new MemoryStream();
- byte[] buffer = null;
- using (ZipFile file = ZipFile.Create(ms))
- {
- file.BeginUpdate();
- //file.NameTransform = new ZipNameTransform();
- file.NameTransform = new MyNameTransfom();
- foreach (var item in files)
- {
- if (File.Exists(item)) file.Add(item);
- }
- file.CommitUpdate();
- buffer = new byte[ms.Length];
- ms.Position = 0;
- ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
- ms.Flush();
- ms.Close();
- }
- Response.Clear();
- Response.Buffer = true;
- Response.ContentType = "application/x-zip-compressed";
- Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
- Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
- Response.BinaryWrite(buffer);
- Page.Response.Flush();
- for (int i = 0; i < files.Count; i++)
- {
- if (onlyDownFile != 1 && isFromClient != 1)
- updateIsDownSuccess(userId, ctidLst[i]);
- }
- }
- //public static object downfileObj = new object();
- private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
- {
- string filePath = file;
- string dfile = Path.GetFileName(file);
- FileStream fs = new FileStream(filePath, FileMode.Open);
- byte[] bytes = new byte[(int)fs.Length];
- fs.Read(bytes, 0, bytes.Length);
- fs.Close();
- Response.Clear();
- //
- Response.ClearContent();
- Response.ClearHeaders();
- Response.ContentType = "application/octet-stream";
- //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
- Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
- //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
- Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
- Response.AddHeader("Content-Length", bytes.Length.ToString());
- Response.BinaryWrite(bytes);
- Response.Flush();
- if (onlyDownFile != 1 && isFromClient != 1)
- updateIsDownSuccess(userId, ctid);
- }
- }
|