This commit is contained in:
2025-02-20 15:08:30 +08:00
commit b40b82d812
87 muutettua tiedostoa jossa 86078 lisäystä ja 0 poistoa
+3
Näytä tiedosto
@@ -0,0 +1,3 @@
packages/*
.vs/*
UploadWeb/*
+30
Näytä tiedosto
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
/// <summary>
/// Nameing 的摘要说明
/// </summary>
public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
{
#region INameTransform
public string TransformDirectory(string name)
{
return null;
}
public string TransformFile(string name)
{
return Path.GetFileName(name);
}
#endregion
}
+138
Näytä tiedosto
@@ -0,0 +1,138 @@
using EnterpriseDT.Net.Ftp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
/// <summary>
/// Nameing 的摘要说明
/// </summary>
public class UpLoadFile
{
FTPConnection ftpConnection;
public Boolean flag;
public static string fileName1;
public static int INV_ORG_ID;
public UpLoadFile()
{
}
//"192.168.0.187";
#region ftp + void InitFtpConnect()
/// <summary>
/// 初始化文件传输ftp
/// </summary>
private void InitFtpConnect()
{
flag = false;
if (this.ftpConnection == null)
{
this.ftpConnection = new FTPConnection();
//this.ftpConnection.ParentControl = this.fQ;
this.ftpConnection.StrictReturnCodes = true;
this.ftpConnection.Timeout = 15000;
//this.ftpConnection.ServerAddress = "120.76.96.55";// "192.168.0.187";//ftpInfo.FtpSeverIP;
this.ftpConnection.ServerAddress = "101.37.27.113";// "192.168.0.187";//ftpInfo.FtpSeverIP;
this.ftpConnection.ServerPort = 21;//ftpInfo.FtpPort;
this.ftpConnection.UserName = "autoorder";// ftpInfo.FtpUser;
this.ftpConnection.Password = "86435015";// ftpInfo.FtpPassword;
//this.ftpConnection.DataEncoding = System.Text.Encoding.GetEncoding("UTF-8");
this.ftpConnection.CommandEncoding = System.Text.Encoding.GetEncoding("GBK");
this.ftpConnection.Uploaded += new FTPFileTransferEventHandler(Uploaded_Finished);
}
}
string msg = "上传失败";
int transFileSize = 0;
public string upLoadFile(string type, string path, string servicePath, string JpgPath, string JpgservicePath)
{
ftpConnection.UploadFile(path, servicePath, false);//上传 cdr 或pdf
ftpConnection.UploadFile(JpgPath, JpgservicePath, false);//上传 cdr 或pdf
return msg;
}
//修改名字的方法
#region
private void RenameFile(object sender, FTPFileRenameEventArgs e)
{
//fileName1 原名包括路径
//fileName2 新名字
if (ftpConnection.Exists(fileName1))
fileName1 = GetNewFileName(fileName1);
ftpConnection.RenameFile("原名", fileName1);
}
#endregion
#endregion
void Uploaded_Finished(object objs, FTPFileTransferEventArgs e)
{
msg = "上传成功";
flag = true;
}
//开始上传
public bool uploadFilName(string LocaTionPath, string newFilename)
{
InitFtpConnect();
if (!ftpConnection.IsConnected)
ftpConnection.Connect();
//新文件夹名
this.ftpConnection.UploadFile(LocaTionPath, newFilename);
this.ftpConnection.Close();
return flag;
}
#region
public void downFile(string filePath)
{
InitFtpConnect();
if (!ftpConnection.IsConnected)
ftpConnection.Connect();
this.ftpConnection.DownloadByteArray(filePath);
}
#endregion
//防止文件重命名
public static string GetNewFileName(string FileName)
{
Random rand = new Random();
string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "m" +
DateTime.Now.Day.ToString() + "d"
+ DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
+ DateTime.Now.Millisecond.ToString()
+ "a" + rand.Next(1000).ToString()
+ FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
return newfilename;
}
}
+912
Näytä tiedosto
@@ -0,0 +1,912 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
/// <summary>
/// Http连接操作帮助类
/// </summary>
public class HttpHelper
{
#region
//默认的编码
private Encoding encoding = Encoding.Default;
//Post数据编码
private Encoding postencoding = Encoding.Default;
//HttpWebRequest对象用来发起请求
private HttpWebRequest request = null;
//获取影响流的数据对象
private HttpWebResponse response = null;
#endregion
#region Public
private string _httpUserAgent = "";
public string HttpUserAgent
{
get { return _httpUserAgent; }
set { _httpUserAgent = value; }
}
/// <summary>
/// 根据相传入的数据,得到相应页面数据
/// </summary>
/// <param name="item">参数类对象</param>
/// <returns>返回HttpResult类型</returns>
public HttpResult GetHtml(HttpItem item)
{
//返回参数
HttpResult result = new HttpResult();
try
{
//准备参数
SetRequest(item);
}
catch (Exception ex)
{
result.Cookie = string.Empty;
result.Header = null;
result.Html = ex.Message;
result.StatusDescription = "配置参数时出错:" + ex.Message;
//配置参数时出错
return result;
}
try
{
//请求数据
using (response = (HttpWebResponse)request.GetResponse())
{
GetData(item, result);
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (response = (HttpWebResponse)ex.Response)
{
GetData(item, result);
}
}
else
{
result.Html = ex.Message;
}
}
catch (Exception ex)
{
result.Html = ex.Message;
}
if (item.IsToLower) result.Html = result.Html.ToLower();
return result;
}
#endregion
#region GetData
/// <summary>
/// 获取数据的并解析的方法
/// </summary>
/// <param name="item"></param>
/// <param name="result"></param>
private void GetData(HttpItem item, HttpResult result)
{
#region base
//获取StatusCode
result.StatusCode = response.StatusCode;
//获取StatusDescription
result.StatusDescription = response.StatusDescription;
//获取最后访问的URl
result.ResponseUri = response.ResponseUri.ToString();
//获取Headers
result.Header = response.Headers;
//获取CookieCollection
if (response.Cookies != null) result.CookieCollection = response.Cookies;
//获取set-cookie
if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
#endregion
#region byte
//处理网页Byte
byte[] ResponseByte = GetByte();
#endregion
#region Html
if (ResponseByte != null & ResponseByte.Length > 0)
{
//设置编码
SetEncoding(item, result, ResponseByte);
//得到返回的HTML
result.Html = encoding.GetString(ResponseByte);
}
else
{
//没有返回任何Html代码
result.Html = string.Empty;
}
#endregion
}
/// <summary>
/// 设置编码
/// </summary>
/// <param name="item">HttpItem</param>
/// <param name="result">HttpResult</param>
/// <param name="ResponseByte">byte[]</param>
private void SetEncoding(HttpItem item, HttpResult result, byte[] ResponseByte)
{
//是否返回Byte类型数据
if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
//从这里开始我们要无视编码了
if (encoding == null)
{
Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta[^<]*charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
string c = string.Empty;
if (meta != null && meta.Groups.Count > 0)
{
c = meta.Groups[1].Value.ToLower().Trim();
}
if (c.Length > 2)
{
try
{
encoding = Encoding.GetEncoding(c.Replace("\"", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
}
catch
{
if (string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
else
{
if (string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
}
/// <summary>
/// 提取网页Byte
/// </summary>
/// <returns></returns>
private byte[] GetByte()
{
byte[] ResponseByte = null;
MemoryStream _stream = new MemoryStream();
//GZIIP处理
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
//开始读取流并设置编码方式
_stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
}
else
{
//开始读取流并设置编码方式
_stream = GetMemoryStream(response.GetResponseStream());
}
//获取Byte
ResponseByte = _stream.ToArray();
_stream.Close();
return ResponseByte;
}
/// <summary>
/// 4.0以下.net版本取数据使用
/// </summary>
/// <param name="streamResponse">流</param>
private MemoryStream GetMemoryStream(Stream streamResponse)
{
MemoryStream _stream = new MemoryStream();
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = streamResponse.Read(buffer, 0, Length);
while (bytesRead > 0)
{
_stream.Write(buffer, 0, bytesRead);
bytesRead = streamResponse.Read(buffer, 0, Length);
}
return _stream;
}
#endregion
#region SetRequest
/// <summary>
/// 为请求准备参数
/// </summary>
///<param name="item">参数列表</param>
private void SetRequest(HttpItem item)
{
// 验证证书
SetCer(item);
//设置Header参数
if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
{
request.Headers.Add(key, item.Header[key]);
}
// 设置代理
//SetProxy(item);
if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
if (!item.Expect100Continue) request.ServicePoint.Expect100Continue = item.Expect100Continue;
//请求方式Get或者Post
request.Method = item.Method;
request.Timeout = item.Timeout;
request.KeepAlive = item.KeepAlive;
request.ReadWriteTimeout = item.ReadWriteTimeout;
if (item.IfModifiedSince != null) request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
//Accept
request.Accept = item.Accept;
//ContentType返回类型
request.ContentType = item.ContentType;
//UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
if (HttpUserAgent != "") request.UserAgent=HttpUserAgent;
else request.UserAgent = item.UserAgent;
// 编码
encoding = item.Encoding;
//设置安全凭证
request.Credentials = item.ICredentials;
//设置Cookie
SetCookie(item);
//来源地址
request.Referer = item.Referer;
//是否执行跳转功能
request.AllowAutoRedirect = item.Allowautoredirect;
if (item.MaximumAutomaticRedirections > 0)
{
request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
}
//设置Post数据
SetPostData(item);
//设置最大连接
if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
}
/// <summary>
/// 设置证书
/// </summary>
/// <param name="item"></param>
private void SetCer(HttpItem item)
{
if (!string.IsNullOrEmpty(item.CerPath))
{
//这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
//初始化对像,并设置请求的URL地址
request = (HttpWebRequest)WebRequest.Create(item.URL);
SetCerList(item);
//将证书添加到请求里
request.ClientCertificates.Add(new X509Certificate(item.CerPath));
}
else
{
//初始化对像,并设置请求的URL地址
request = (HttpWebRequest)WebRequest.Create(item.URL);
SetCerList(item);
}
}
/// <summary>
/// 设置多个证书
/// </summary>
/// <param name="item"></param>
private void SetCerList(HttpItem item)
{
if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
{
foreach (X509Certificate c in item.ClentCertificates)
{
request.ClientCertificates.Add(c);
}
}
}
/// <summary>
/// 设置Cookie
/// </summary>
/// <param name="item">Http参数</param>
private void SetCookie(HttpItem item)
{
if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
//设置CookieCollection
if (item.ResultCookieType == ResultCookieType.CookieCollection)
{
request.CookieContainer = new CookieContainer();
if (item.CookieCollection != null && item.CookieCollection.Count > 0)
request.CookieContainer.Add(item.CookieCollection);
}
}
/// <summary>
/// 设置Post数据
/// </summary>
/// <param name="item">Http参数</param>
private void SetPostData(HttpItem item)
{
//验证在得到结果时是否有传入数据
if (!request.Method.Trim().ToLower().Contains("get"))
{
if (item.PostEncoding != null)
{
postencoding = item.PostEncoding;
}
byte[] buffer = null;
//写入Byte类型
if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
{
//验证在得到结果时是否有传入数据
buffer = item.PostdataByte;
}//写入文件
else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(item.Postdata))
{
StreamReader r = new StreamReader(item.Postdata, postencoding);
buffer = postencoding.GetBytes(r.ReadToEnd());
r.Close();
} //写入字符串
else if (!string.IsNullOrEmpty(item.Postdata))
{
buffer = postencoding.GetBytes(item.Postdata);
}
if (buffer != null)
{
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
}
}
/// <summary>
/// 设置代理
/// </summary>
/// <param name="item">参数对象</param>
private void SetProxy(HttpItem item)
{
bool isIeProxy = false;
if (!string.IsNullOrEmpty(item.ProxyIp))
{
isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
}
if (!string.IsNullOrEmpty(item.ProxyIp) && !isIeProxy)
{
//设置代理服务器
if (item.ProxyIp.Contains(":"))
{
string[] plist = item.ProxyIp.Split(':');
WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
//建议连接
myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
//给当前请求对象
request.Proxy = myProxy;
}
else
{
WebProxy myProxy = new WebProxy(item.ProxyIp, false);
//建议连接
myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
//给当前请求对象
request.Proxy = myProxy;
}
}
else if (isIeProxy)
{
//设置为IE代理
}
else
{
request.Proxy = item.WebProxy;
}
}
#endregion
#region private main
/// <summary>
/// 回调验证证书问题
/// </summary>
/// <param name="sender">流对象</param>
/// <param name="certificate">证书</param>
/// <param name="chain">X509Chain</param>
/// <param name="errors">SslPolicyErrors</param>
/// <returns>bool</returns>
private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
#endregion
}
/// <summary>
/// Http请求参考类
/// </summary>
public class HttpItem
{
string _URL = string.Empty;
/// <summary>
/// 请求URL必须填写
/// </summary>
public string URL
{
get { return _URL; }
set { _URL = value; }
}
string _Method = "GET";
/// <summary>
/// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值
/// </summary>
public string Method
{
get { return _Method; }
set { _Method = value; }
}
int _Timeout = 100000;
/// <summary>
/// 默认请求超时时间
/// </summary>
public int Timeout
{
get { return _Timeout; }
set { _Timeout = value; }
}
int _ReadWriteTimeout = 30000;
/// <summary>
/// 默认写入Post数据超时间
/// </summary>
public int ReadWriteTimeout
{
get { return _ReadWriteTimeout; }
set { _ReadWriteTimeout = value; }
}
Boolean _KeepAlive = true;
/// <summary>
/// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。
/// </summary>
public Boolean KeepAlive
{
get { return _KeepAlive; }
set { _KeepAlive = value; }
}
string _Accept = "text/html, application/xhtml+xml, */*";
/// <summary>
/// 请求标头值 默认为text/html, application/xhtml+xml, */*
/// </summary>
public string Accept
{
get { return _Accept; }
set { _Accept = value; }
}
string _ContentType = "text/html";
/// <summary>
/// 请求返回类型默认 text/html
/// </summary>
public string ContentType
{
get { return _ContentType; }
set { _ContentType = value; }
}
string _UserAgent = "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36";
/// <summary>
/// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
/// </summary>
public string UserAgent
{
get { return _UserAgent; }
set { _UserAgent = value; }
}
Encoding _Encoding = null;
/// <summary>
/// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312
/// </summary>
public Encoding Encoding
{
get { return _Encoding; }
set { _Encoding = value; }
}
private PostDataType _PostDataType = PostDataType.String;
/// <summary>
/// Post的数据类型
/// </summary>
public PostDataType PostDataType
{
get { return _PostDataType; }
set { _PostDataType = value; }
}
string _Postdata = string.Empty;
/// <summary>
/// Post请求时要发送的字符串Post数据
/// </summary>
public string Postdata
{
get { return _Postdata; }
set { _Postdata = value; }
}
private byte[] _PostdataByte = null;
/// <summary>
/// Post请求时要发送的Byte类型的Post数据
/// </summary>
public byte[] PostdataByte
{
get { return _PostdataByte; }
set { _PostdataByte = value; }
}
private WebProxy _WebProxy;
/// <summary>
/// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp
/// </summary>
public WebProxy WebProxy
{
get { return _WebProxy; }
set { _WebProxy = value; }
}
CookieCollection cookiecollection = null;
/// <summary>
/// Cookie对象集合
/// </summary>
public CookieCollection CookieCollection
{
get { return cookiecollection; }
set { cookiecollection = value; }
}
string _Cookie = string.Empty;
/// <summary>
/// 请求时的Cookie
/// </summary>
public string Cookie
{
get { return _Cookie; }
set { _Cookie = value; }
}
string _Referer = string.Empty;
/// <summary>
/// 来源地址,上次访问地址
/// </summary>
public string Referer
{
get { return _Referer; }
set { _Referer = value; }
}
string _CerPath = string.Empty;
/// <summary>
/// 证书绝对路径
/// </summary>
public string CerPath
{
get { return _CerPath; }
set { _CerPath = value; }
}
private Boolean isToLower = false;
/// <summary>
/// 是否设置为全文小写,默认为不转化
/// </summary>
public Boolean IsToLower
{
get { return isToLower; }
set { isToLower = value; }
}
private Boolean allowautoredirect = false;
/// <summary>
/// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转
/// </summary>
public Boolean Allowautoredirect
{
get { return allowautoredirect; }
set { allowautoredirect = value; }
}
private int connectionlimit = 1024;
/// <summary>
/// 最大连接数
/// </summary>
public int Connectionlimit
{
get { return connectionlimit; }
set { connectionlimit = value; }
}
private string proxyusername = string.Empty;
/// <summary>
/// 代理Proxy 服务器用户名
/// </summary>
public string ProxyUserName
{
get { return proxyusername; }
set { proxyusername = value; }
}
private string proxypwd = string.Empty;
/// <summary>
/// 代理 服务器密码
/// </summary>
public string ProxyPwd
{
get { return proxypwd; }
set { proxypwd = value; }
}
private string proxyip = string.Empty;
/// <summary>
/// 代理 服务IP ,如果要使用IE代理就设置为ieproxy
/// </summary>
public string ProxyIp
{
get { return proxyip; }
set { proxyip = value; }
}
private ResultType resulttype = ResultType.String;
/// <summary>
/// 设置返回类型String和Byte
/// </summary>
public ResultType ResultType
{
get { return resulttype; }
set { resulttype = value; }
}
private WebHeaderCollection header = new WebHeaderCollection();
/// <summary>
/// header对象
/// </summary>
public WebHeaderCollection Header
{
get { return header; }
set { header = value; }
}
private Version _ProtocolVersion;
/// <summary>
// 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。
/// </summary>
public Version ProtocolVersion
{
get { return _ProtocolVersion; }
set { _ProtocolVersion = value; }
}
private Boolean _expect100continue = true;
/// <summary>
/// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。
/// </summary>
public Boolean Expect100Continue
{
get { return _expect100continue; }
set { _expect100continue = value; }
}
private X509CertificateCollection _ClentCertificates;
/// <summary>
/// 设置509证书集合
/// </summary>
public X509CertificateCollection ClentCertificates
{
get { return _ClentCertificates; }
set { _ClentCertificates = value; }
}
private Encoding _PostEncoding;
/// <summary>
/// 设置或获取Post参数编码,默认的为Default编码
/// </summary>
public Encoding PostEncoding
{
get { return _PostEncoding; }
set { _PostEncoding = value; }
}
private ResultCookieType _ResultCookieType = ResultCookieType.String;
/// <summary>
/// Cookie返回类型,默认的是只返回字符串类型
/// </summary>
public ResultCookieType ResultCookieType
{
get { return _ResultCookieType; }
set { _ResultCookieType = value; }
}
private ICredentials _ICredentials = CredentialCache.DefaultCredentials;
/// <summary>
/// 获取或设置请求的身份验证信息。
/// </summary>
public ICredentials ICredentials
{
get { return _ICredentials; }
set { _ICredentials = value; }
}
/// <summary>
/// 设置请求将跟随的重定向的最大数目
/// </summary>
private int _MaximumAutomaticRedirections;
public int MaximumAutomaticRedirections
{
get { return _MaximumAutomaticRedirections; }
set { _MaximumAutomaticRedirections = value; }
}
private DateTime? _IfModifiedSince = null;
/// <summary>
/// 获取和设置IfModifiedSince,默认为当前日期和时间
/// </summary>
public DateTime? IfModifiedSince
{
get { return _IfModifiedSince; }
set { _IfModifiedSince = value; }
}
}
/// <summary>
/// Http返回参数类
/// </summary>
public class HttpResult
{
private string _Cookie;
/// <summary>
/// Http请求返回的Cookie
/// </summary>
public string Cookie
{
get { return _Cookie; }
set { _Cookie = value; }
}
private CookieCollection _CookieCollection;
/// <summary>
/// Cookie对象集合
/// </summary>
public CookieCollection CookieCollection
{
get { return _CookieCollection; }
set { _CookieCollection = value; }
}
private string _html = string.Empty;
/// <summary>
/// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空
/// </summary>
public string Html
{
get { return _html; }
set { _html = value; }
}
private byte[] _ResultByte;
/// <summary>
/// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空
/// </summary>
public byte[] ResultByte
{
get { return _ResultByte; }
set { _ResultByte = value; }
}
private Dictionary<string, string> _dicHeaders;
public Dictionary<string, string> dicHeaders
{
get { return _dicHeaders; }
set { _dicHeaders = value; }
}
private Dictionary<string, string> _setCookies=new Dictionary<string, string>();
public Dictionary<string, string> setCookies
{
get { return _setCookies; }
set { _setCookies = value; }
}
private string _lastCookie;
public string lastCookies
{
get { return _lastCookie; }
set { _lastCookie = value; }
}
private string _location;
public string Location
{
get { return _location; }
set { _location = value; }
}
private WebHeaderCollection _Header;
/// <summary>
/// header对象
/// </summary>
public WebHeaderCollection Header
{
get { return _Header; }
set { _Header = value; }
}
private string _StatusDescription;
/// <summary>
/// 返回状态说明
/// </summary>
public string StatusDescription
{
get { return _StatusDescription; }
set { _StatusDescription = value; }
}
private HttpStatusCode _StatusCode;
/// <summary>
/// 返回状态码,默认为OK
/// </summary>
public HttpStatusCode StatusCode
{
get { return _StatusCode; }
set { _StatusCode = value; }
}
/// <summary>
/// 最后访问的URl
/// </summary>
public string ResponseUri { get; set; }
/// <summary>
/// 获取重定向的URl
/// </summary>
public string RedirectUrl
{
get
{
try
{
if (Header != null && Header.Count > 0)
{
if (Header["location"]!=null)
{
string locationurl = Header["location"].ToString().ToLower();
if (!string.IsNullOrEmpty(locationurl))
{
bool b = locationurl.StartsWith("http://") || locationurl.StartsWith("https://");
if (!b)
{
locationurl = new Uri(new Uri(ResponseUri), locationurl).AbsoluteUri;
}
}
return locationurl;
}
}
}
catch { }
return string.Empty;
}
}
}
/// <summary>
/// 返回类型
/// </summary>
public enum ResultType
{
/// <summary>
/// 表示只返回字符串 只有Html有数据
/// </summary>
String,
/// <summary>
/// 表示返回字符串和字节流 ResultByte和Html都有数据返回
/// </summary>
Byte
}
/// <summary>
/// Post的数据格式默认为string
/// </summary>
public enum PostDataType
{
/// <summary>
/// 字符串类型,这时编码Encoding可不设置
/// </summary>
String,
/// <summary>
/// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空
/// </summary>
Byte,
/// <summary>
/// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值
/// </summary>
FilePath
}
/// <summary>
/// Cookie返回类型
/// </summary>
public enum ResultCookieType
{
/// <summary>
/// 只返回字符串类型的Cookie
/// </summary>
String,
/// <summary>
/// CookieCollection格式的Cookie集合同时也返回String类型的cookie
/// </summary>
CookieCollection
}
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>G:\git\upload-release</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<PrecompileBeforePublish>true</PrecompileBeforePublish>
<EnableUpdateable>false</EnableUpdateable>
<DebugSymbols>false</DebugSymbols>
<WDPMergeOption>CreateSeparateAssembly</WDPMergeOption>
<UseFixedNames>true</UseFixedNames>
</PropertyGroup>
</Project>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<History>True|2025-01-20T07:50:57.4911021Z;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>
BIN
Näytä tiedosto
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+32450
Näytä tiedosto
File diff suppressed because it is too large Load Diff
+40
Näytä tiedosto
@@ -0,0 +1,40 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="http://localhost:911/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
//$(function () {
// var param = "{'account':'admin','method': 'api00001','time':'1434524987331','signature':'b18d3cdf8cc8dcc666604bb822eed09a'}";
// $.ajax({
// type: 'post',
// headers: { 'Access-Control-Allow-Origin': '*' },
// url: 'http://api.zjyypt.net.net/v1/openapi.htm',
// useDefaultXhrHeader: false,
// crossDomain: true,
// dataType: "json",
// data: {
// param: "{'account':'admin','method': 'api00001','time':'1434524987331','signature':'b18d3cdf8cc8dcc666604bb822eed09a'}"
// },
// success: function (d) {
// alert(d);
// //$('body').html(d.status);
// }
// });
// //$.post("http://api.zjyypt.net.net/v1/openapi.htm", { "param": param }, function (data) {
// // alert(data); //业务... });
// //});
//});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
+115
Näytä tiedosto
@@ -0,0 +1,115 @@
using BizCom;
using SevenZip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string fileName = "(C2_1975999718512169836)-80x40mm-1000张-不干胶铜版纸烫金覆膜模切--YJSJ-郑凌宇1-四川省-金陵-[C2].cdr";
//string ctid = MidStrEx(fileName, "(", ")").Trim();
// CeErpTradeCell entity=CeErpTradeCell.GetByCtid("C2_1975999718512169836");
//entity.Update();
//Response.Write(entity.ctid + "<br>");
//if (IntPtr.Size == 4)
//{
// SevenZipCompressor.SetLibraryPath(@"D:\fireant\ecomerp\UploadWeb\Bin\x64\7z.dll");
//}
//else
//{
// SevenZipCompressor.SetLibraryPath(@"D:\fireant\ecomerp\UploadWeb\Bin\x86\7z.dll");
//}
//SevenZipCompressor.SetLibraryPath(@"D:\fireant\ecomerp\UploadWeb\Bin\x64\7z.dll");
//SevenZipExtractor.SetLibraryPath(@"\x64\7z.dll");
//SevenZip.SevenZipExtractor
//LibraryFeature lf = SevenZipExtractor.CurrentLibraryFeatures;
SevenZipExtractor.SetLibraryPath(Server.MapPath("bin\\7z.dll"));
//var path = Path.Combine(Server.MapPath("bin"), Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");
//SevenZip.SevenZipBase.SetLibraryPath(path);
//SevenZipExtractor.SetLibraryPath(path);
//using (SevenZipExtractor szExtra = new SevenZipExtractor("d:\\4.rar"))
// {
//szExtra.ExtractArchive("d:\\temp");
// foreach (string afn in szExtra.ArchiveFileNames)
//{
//if (afn.IndexOf("123123", StringComparison.OrdinalIgnoreCase) != -1)
// szExtra.ExtractFiles("d:\\temp", afn);
// }
//}
}
private void CdrExportPng(string path, string cdrFile)
{
if (!File.Exists(cdrFile))
{
Response.Write("找不到文件:"+cdrFile);
return;
}
string fname = path + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png";
CorelDRAW.Application cdr = new CorelDRAW.Application();
cdr.OpenDocument(cdrFile, 1);
object obj = new object();
Response.Write(Utils.Serialization.JsonString.Convert(cdr.ActiveDocument.ActiveLayer.Shapes[0]));
return;
cdr.ActiveDocument.ExportBitmap(
fname,
CorelDRAW.cdrFilter.cdrPNG,
CorelDRAW.cdrExportRange.cdrCurrentPage,
CorelDRAW.cdrImageType.cdrRGBColorImage,
0, 0, 72, 72,
CorelDRAW.cdrAntiAliasingType.cdrNoAntiAliasing,
false,
true,
true,
false,
CorelDRAW.cdrCompressionType.cdrCompressionNone,
null).Finish();
cdr.ActiveDocument.Close();
cdr.Quit();
}
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
Console.WriteLine("MidStrEx Err:" + ex.Message);
}
return result;
}
private string formatMemo(object memo)
{
string m = memo.ToString();
m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
return m;
}
}
+79
Näytä tiedosto
@@ -0,0 +1,79 @@
<%@ Application Language="C#" %>
<%@ Import Namespace="Castle.ActiveRecord" %>
<%@ Import Namespace="Castle.ActiveRecord.Framework.Config" %>
<%@ Import Namespace="BizCom" %>
<%@ Import Namespace="Utils" %>
<%@ Import Namespace="System.Threading" %>
<script RunAt="server">
System.Threading.Timer gtimer;
void Application_Start(object sender, EventArgs e)
{
//log4net.Config.XmlConfigurator.Configure();
// Code that runs on application startup
InPlaceConfigurationSource source = new InPlaceConfigurationSource();
System.Collections.Generic.IDictionary<string, string> properties = new System.Collections.Generic.Dictionary<string, string>();
properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle");
properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
properties.Add("connection.connection_string", SecurityHelper.DecryptSymmetric(conn));
source.Add(typeof(ActiveRecordBase), properties);
source.IsRunningInWebApp = true;
//IConfigurationSource source =ConfigurationManager.GetSection("activerecord") as IConfigurationSource;
Type[] acTypes = new[]
{
typeof(CeErpTrade),
typeof(CeErpTradeCell),
typeof(XLog),
typeof(CeErpTradeLog),
typeof(CeErpDataSendOrderInfo),
};
ActiveRecordStarter.Initialize(source, acTypes);
}
void global_elapsed(object state)
{
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_BeginRequest(Object sender, EventArgs e)
{
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
//if (config.Instance.Site.SpiderIp.Contains(CommonHelper.ClientIP))return;
//SyLog.WriteLog(Server.GetLastError());
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NeedDownList.aspx.cs" Inherits="NeedDownList" %>
+54
Näytä tiedosto
@@ -0,0 +1,54 @@
using SiteCore.Redis;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class NeedDownList : System.Web.UI.Page
{
private void conSuc(string msg)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
//Response.End();
}
private void conErc(string msg)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Write("{\"type\":\"error\",\"result\":\"" + msg + "!\"}");
//Response.End();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int userId = 0;
if (Request["userid"] != null)
{
userId = Convert.ToInt32(Request["userid"]);
}
if (userId<=0)
{
conErc("缺少必要的参数");
return;
}
string key = "file_client_down_list_" + userId;
string data = erpRedis.RedisHelper.ListRightPop<string>(key);
if (data == null)
data = "";
conSuc(data);
}
}
}
Näytä tiedosto
+41
Näytä tiedosto
@@ -0,0 +1,41 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34221.43
MinimumVisualStudioVersion = 10.0.40219.1
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "UploadWeb(1)", ".", "{ED18D3B6-538B-47CA-9CFA-60B890612930}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.8.1"
Debug.AspNetCompiler.VirtualPath = "/localhost_54673"
Debug.AspNetCompiler.PhysicalPath = "..\UploadWeb\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_54673\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.FixedNames = "false"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/localhost_54673"
Release.AspNetCompiler.PhysicalPath = "..\UploadWeb\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_54673\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.FixedNames = "false"
Release.AspNetCompiler.Debug = "False"
VWDPort = "54673"
SlnRelativePath = "..\UploadWeb\"
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{ED18D3B6-538B-47CA-9CFA-60B890612930}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ED18D3B6-538B-47CA-9CFA-60B890612930}.Debug|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5D88026A-4AC6-4787-B9F4-B6EDE7C80384}
EndGlobalSection
EndGlobal
+146
Näytä tiedosto
@@ -0,0 +1,146 @@
<?xml version="1.0"?>
<configuration>
<configSections>
<!--activerecord的配置-->
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>
</configSections>
<connectionStrings>
<add name="RedisConn" connectionString="127.0.0.1:6379,password=,allowAdmin=true"/>
<!--正式-->
<add name="ConnString" connectionString="waSaLjFS1MAAoSe9+gKWJQ1CDnZ6dnO1QM0VzexKlXubMo4FCxLb4bGGAU51LHdcMfZxFkJQRZYr0VE6xFGB7Kpc8NKm8oz5p/9017hMVXqnAFPNyQ0zlOCGtSn5SrZEwFoWi1DEWddm1Qa251ScTdaiUfKARB9gsjoXWWM6JnnBGsHvhHU7EMZtm4NsIlz6xKpZh3BNuuLI75CDc6r68YjHv+FyfOAK"/>
<add name="ConnString2" connectionString="waSaLjFS1MAAoSe9+gKWJQ1CDnZ6dnO1QM0VzexKlXubMo4FCxLb4bGGAU51LHdcMfZxFkJQRZYr0VE6xFGB7Kpc8NKm8oz5p/9017hMVXqnAFPNyQ0zlOCGtSn5SrZEwFoWi1DEWddm1Qa251ScTdaiUfKARB9gsjoXWWM6JnnBGsHvhHU7EMZtm4NsIlz6ARKPn6RYCp2Zza8Ht7FTpX+ivahgu7qH"/>
</connectionStrings>
<appSettings>
<add key="vs:EnableBrowserLink" value="false"/>
<add key="upPath" value="G:\_YangCai\upload"/>
<add key="curPath" value="G:\_YangCai\upload"/>
<add key="copyPath" value="G:\fireant\ecomerp\document\copy"/>
<add key="dPath" value="D:\fireant\ecomerp\document"/>
<add key="OriSiteUrl" value="http://localhost:911/Handler/sync.ashx?t=file_downback"/>
</appSettings>
<!--activerecord的配置-->
<activerecord>
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.connection_string" value="ConnectionString = ${ConnString}"/>
</config>
</activerecord>
<location>
<system.web>
<!-- <compilation targetFramework="2.0" debug="true"/>
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
-->
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
-->
<customErrors mode="RemoteOnly" defaultRedirect="ErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
<!--
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="web" namespace="WebUI.WebControls" assembly="WebUI"/>
</controls>
</pages>
-->
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>
<httpModules>
<!--<remove name="Session" />-->
<remove name="WindowsAuthentication"/>
<remove name="PassportAuthentication"/>
<remove name="AnonymousIdentification"/>
<remove name="UrlAuthorization"/>
<remove name="FileAuthorization"/>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
<httpRuntime requestValidationMode="2.0" maxRequestLength="73400000" executionTimeout="300" appRequestQueueLimit="100"/>
<!--<identity impersonate="true" userName="xjh_develop" password="123123"/>-->
</system.web>
</location>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<location>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="false">
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="HttpHandler-32"/>
<remove name="HttpHandler"/>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
<defaultDocument>
<files>
<clear/>
<add value="index.html"/>
<add value="index.aspx"/>
<add value="/"/>
<add value="default.aspx"/>
</files>
</defaultDocument>
<httpProtocol allowKeepAlive="true">
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
</customHeaders>
</httpProtocol>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="419430400"/>
</requestFiltering>
</security>
</system.webServer>
</location>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<!--
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。
可在 <httpRuntime> 标记上设置以下特性。
<system.Web>
<httpRuntime targetFramework="4.8.1" />
</system.Web>
-->
<system.web>
<compilation targetFramework="4.8.1" debug="true"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
</configuration>
+145
Näytä tiedosto
@@ -0,0 +1,145 @@
<?xml version="1.0"?>
<configuration>
<configSections>
<!--activerecord的配置-->
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>
</configSections>
<connectionStrings>
<!--正式-->
<add name="ConnString" connectionString="waSaLjFS1MAZf++J/2SZWqMPAJa/7ot9L/cXoI9nWm5Og1G60v7Nyq7xGWdSS/Blpcsb2S9Ir/IJKmzNE6vLTn2WKTMYWEcs9RXoI3Op9n1c5WrAvKzA9Sudl+Y3mHvdwBojvbFoOk+YnRRNJkFQtFrdihg3nDNdME2mXdid9R0cehNfXQEmJQ=="/>
<add name="ConnString2" connectionString="waSaLjFS1MAAoSe9+gKWJQ1CDnZ6dnO1QM0VzexKlXubMo4FCxLb4bGGAU51LHdcMfZxFkJQRZYr0VE6xFGB7Kpc8NKm8oz5p/9017hMVXqnAFPNyQ0zlOCGtSn5SrZEwFoWi1DEWddm1Qa251ScTdaiUfKARB9gsjoXWWM6JnnBGsHvhHU7EMZtm4NsIlz6ARKPn6RYCp2Zza8Ht7FTpX+ivahgu7qH"/>
</connectionStrings>
<appSettings>
<add key="vs:EnableBrowserLink" value="false"/>
<add key="upPath" value="D:\fireant\ecomerp\document\ws"/>
<add key="curPath" value="D:\fireant\ecomerp\document\ws"/>
<add key="copyPath" value="D:\fireant\ecomerp\document\copy"/>
<add key="dPath" value="D:\fireant\ecomerp\document"/>
</appSettings>
<!--activerecord的配置-->
<activerecord>
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.connection_string" value="ConnectionString = ${ConnString}"/>
</config>
</activerecord>
<location>
<system.web>
<compilation targetFramework="4.5" debug="true"/>
<!--
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
-->
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
-->
<customErrors mode="RemoteOnly" defaultRedirect="ErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="web" namespace="WebUI.WebControls" assembly="WebUI"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>
<httpModules>
<!--<remove name="Session" />-->
<remove name="WindowsAuthentication"/>
<remove name="PassportAuthentication"/>
<remove name="AnonymousIdentification"/>
<remove name="UrlAuthorization"/>
<remove name="FileAuthorization"/>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
<httpRuntime requestValidationMode="2.0" maxRequestLength="73400000" executionTimeout="300" appRequestQueueLimit="100"/>
<!--<identity impersonate="true" userName="xjh_develop" password="123123"/>-->
</system.web>
</location>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<location>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="false">
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="HttpHandler-32"/>
<remove name="HttpHandler"/>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
<defaultDocument>
<files>
<clear/>
<add value="index.html"/>
<add value="index.aspx"/>
<add value="/"/>
<add value="default.aspx"/>
</files>
</defaultDocument>
<httpProtocol allowKeepAlive="true">
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
</customHeaders>
</httpProtocol>
<staticContent>
<mimeMap fileExtension=".apk" mimeType="application/octet-stream"/>
<mimeMap fileExtension=".json" mimeType="application/json"/>
<mimeMap fileExtension=".woff" mimeType="application/x-font-woff"/>
<mimeMap fileExtension=".woff2" mimeType="application/x-font-woff"/>
<clientCache cacheControlMode="NoControl" cacheControlMaxAge="01:00:00"/>
</staticContent>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="419430400" />
</requestFiltering>
</security>
</system.webServer>
</location>
<!--
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。
可在 <httpRuntime> 标记上设置以下特性。
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="autocopy.aspx.cs" Inherits="autocopy" %>
+363
Näytä tiedosto
@@ -0,0 +1,363 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using SQLData;
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;
using System.Web.UI.WebControls;
public partial class autocopy : System.Web.UI.Page
{
public static string upPath = ConfigurationManager.AppSettings["upPath"];
public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
private void conErc(string msg)
{
Response.Write("{\"type\":\"error\",\"result\":\"" + 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 (Request["hexdata"] != null)
{
string tids = Request["hexdata"];
if (tids.Trim() == "")
{
conErc("无法下载");
return;
}
int userId = 0;
if (Request["userid"] != null)
{
userId = Convert.ToInt32(Request["userid"]);
}
try
{
string[] tArr = tids.Split(',');
if (tArr.Length != 2)
{
conErc("订单ID不对,无法下载");
return;
}
string oldctid = tArr[0].ToString();
string newctid = tArr[1].ToString();
StringBuilder sql = new StringBuilder();
sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName from view_erptradecell where ctid='{0}'", oldctid);
DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
if (dt == null || dt.Rows.Count < 1)
{
conErc("没有找到相关订单" + oldctid);
return;
}
StringBuilder sqlnew = new StringBuilder();
sqlnew.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName,orderSn from view_erptradecell where (orderstate=3 or orderstate=4) and ctid='{0}'", newctid);
DataTable dtnew = CeErpTradeCell.ExecuteDataset(sqlnew.ToString()).Tables[0];
if (dtnew == null || dtnew.Rows.Count < 1)
{
conErc("没有找到相关new新订单" + newctid);
return;
}
List<string> files = new List<string>();
string oldDesignTime = "";
string oldFilename = "";
string df_name = "";
string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
string oldTag = ".cdr";
List<string> noFileLst = new List<string>();
List<string> errorFileLst = new List<string>();
DataRow dr = dt.Rows[0];
if (dr["FinishDesignTime"].ToString() == "")
{
conErc("没有找到相关old老订单附件,FinishDesignTime为空");
return;
}
DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
if (ftime.CompareTo(splitTime) > 0)
{
oldDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);
}
else
oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
//oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
df_name = upPath + "\\" + oldDesignTime + "\\" + formatMemo(dr["seller_memo"]);
foreach (string ext in extArr)
{
oldFilename = df_name + ext;
oldTag = ext;
if (File.Exists(oldFilename))
{
break;
//if (!isUpdateError)
//{
// files.Add(fname);
// copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
// fc++;
//}
}
else
oldFilename = "";
}
if (oldFilename == "")
{
conErc("没有找到相关old老订单附件");
return;
//noFileLst.Add("'" + dr["ctid"].ToString() + "'");
}
//if (hasFile)
//{
// fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
// if (File.Exists(fname))
// {
// files.Add(fname);
// copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
// }
//}
//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}) ;", tids, (int)OrderState.下单完成, userId, "下载设计文件");
//sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
//sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
DataRow newDr = dtnew.Rows[0];
string newMemo = newDr["seller_memo"].ToString();
newMemo = newMemo.Replace("", "(");
newMemo = newMemo.Replace("", ")");
string newmemoctid = MidStrEx(newMemo, "(", ")").Trim();
string orderSn = newDr["orderSn"].ToString();
if (newctid.IndexOf("C") != -1)
{
/*if (newMemo.IndexOf("[") != -1 && newMemo.IndexOf("C") != -1)
{
if (newmemoctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1] 对应ctid是 S_S_C1_1962772776865084101
{
int lastIndex = newmemoctid.LastIndexOf("S_"); //最后一个S_的位置
string sPre = newmemoctid.Substring(0, lastIndex + 2); //S_S_
string initTid = newmemoctid.Substring(lastIndex + 2, newmemoctid.Length - lastIndex - 2); //1962772776865084101
string pre_ctid = MidStrEx(newMemo, "[", "]"); //C1
if (pre_ctid.IndexOf("+") != -1)
{
pre_ctid = "C" + pre_ctid.Split('+')[1];
}
newmemoctid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101
}
else
{
string pre_ctid = MidStrEx(newMemo, "[", "]");
if (pre_ctid.IndexOf("+") != -1)
{
pre_ctid = "C" + pre_ctid.Split('+')[1];
}
if (newmemoctid.IndexOf('C') == -1)
{
newmemoctid = pre_ctid + "_" + newmemoctid;
}
}
}*/
}
if (string.IsNullOrEmpty(newmemoctid))
{
conErc("上传的文件名格式不正确");
return;
}
if (orderSn != newmemoctid)
{
conErc("新订单备注中的订单号不正确");
return;
}
string newUpDesignTime = getDesignTimeWithDay(DateTime.Now);
//string newDfName = upPath + "\\" + newUpDesignTime + "\\" + formatMemo(newDr["seller_memo"])+oldTag;
string newPathFileName = "";
copyUpFile(newUpDesignTime, oldFilename, formatMemo(newDr["seller_memo"]) + oldTag, ref newPathFileName);
//copyFile(getDesignDate(DateTime.Now), dr["SupplierName"].ToString(), oldFilename, formatMemo(newDr["seller_memo"]) + oldTag);
CeErpTradeCell.UpdateRelationOrder(newctid);
StringBuilder up_sql = new StringBuilder();
up_sql.AppendFormat("update ce_erptradecell with(rowlock) set orderstate=5,IsReturn=0,StartDesignTime=getdate(),SupplierId={1},FinishDesignTime=getdate() where ctid='{0}'", newctid, dr["SupplierId"]);
CeErpTradeCell.ExecuteNonQuery(up_sql.ToString());
if (oldTag == ".cdr")
{
//string sqlpng = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", newPathFileName);
//CeErpTradeLog.ExecuteNonQuery(sqlpng);
}
CeErpTradeLog.AddLog(newctid, 5, userId, "自动上传老客户文件-" + newPathFileName);
conSuc("文件已上传到共享目录");
return;
}
catch (Exception ex)
{
conErc("错误的下载访问" + ex.Message);
XLog.SaveLog(0, "autocopydown," + ex.Message);
return;
}
}
}
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
Console.WriteLine("MidStrEx Err:" + ex.Message);
}
return result;
}
private string formatMemo(object memo)
{
string m = memo.ToString();
m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
return m;
}
private void copyUpFile(string date, string oldfile, string newfilename, ref string newPathFileName)
{
try
{
string path = upPath + "\\" + date;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
//string fname = Path.GetFileName(file);
File.Copy(oldfile, path + "\\" + newfilename, true);
newPathFileName = path + "\\" + newfilename;
if (!File.Exists(path + "\\" + newfilename))
{
File.Copy(oldfile, path + "\\" + newfilename, true);
}
}
catch (Exception ex)
{
XLog.SaveLog(0, "自动复制上传文件发生错误," + newfilename + "," + ex.Message);
throw ex;
}
}
private void copyFile(string date, string supplier, string oldfile, string newFileName)
{
try
{
string path = copyPath + "\\" + date + "\\" + supplier;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
//string fname = Path.GetFileName(file);
File.Copy(oldfile, path + "\\" + newFileName, true);
if (!File.Exists(path + "\\" + newFileName))
{
File.Copy(oldfile, path + "\\" + newFileName, true);
}
}
catch (Exception ex)
{
XLog.SaveLog(0, "自动复制下载文件发生错误," + oldfile + "," + ex.Message);
}
}
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(List<string> files, string zipFileName)
{
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();
Page.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
//Response.Flush();
//Response.End();
}
private void downLoadFile(string file)
{
string filePath = Server.MapPath("d/" + file);//路径
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="caiyintongload.aspx.cs" Inherits="caiyingtongload" %>
+654
Näytä tiedosto
@@ -0,0 +1,654 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json.Linq;
using SiteCore.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.Security;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Security.Cryptography.X509Certificates;
using Utils;
using System.Runtime.InteropServices;
using NPOI.OpenXmlFormats.Shared;
public partial class caiyingtongload : 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"];
[DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
public static extern uint DecFile(string filename);
[DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
[DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
public static extern void CreateUserKey(StringBuilder key, int len);
[DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
public static extern int InitAesKey(StringBuilder key, int len);
[DllImport("DrvInterface64.dll")]
public static extern int IsInitedAesKey();
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;
downloadcayingtonge();
}
}
private string getCanDownFile(string fileName)
{
string[] extArr = new string[] { ".cdr", ".zip", ".rar" };
foreach (string ext in extArr)
{
string fname = fileName + ext;
if (File.Exists(fname))
{
return fname;
}
}
return "";
}
private void updateIsDownSuccess(int userId, string ctid)
{
try
{
XLog.SaveLog(0, "updateIsDownSuccess ,ctid:" + ctid);
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 downloadcayingtonge()
{
string tids = Request["hexdata"];
int onlyDownFile = 0;//只下文件
if (Request["onlyfile"] != null)
{
Int32.TryParse(Request["onlyfile"], out onlyDownFile);
}
int cyt = 0;
if (Request["cyt"] != null)
{
Int32.TryParse(Request["cyt"], out cyt);
}
int userId = 0;
if (Request["userid"] != null)
{
Int32.TryParse(Request["userid"], out userId);
}
String ui = "";
if (cyt == 1)
{
StringBuilder sql = new StringBuilder();
sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5,IsSF from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1) ? "" : " and OrderState=5 "));
DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
if (dt == null || dt.Rows.Count < 1)
{
conErc("没有找到相关订单");
return;
}
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 fileMd5 = "", fileNames = "";
String seller_memo = "";
int ISSF = 0;
string finishDesignTime = getDesignTime(dr["FinishDesignTime"]);
string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
if (!Convert.IsDBNull(dr["seller_memo"]))
{
seller_memo = dr["seller_memo"].ToString();
}
if (!Convert.IsDBNull(dr["IsSF"]))
{
ISSF = Convert.ToInt32(dr["IsSF"] == null ? 0 : dr["IsSF"]);
}
string fname = getCanDownFile(df_name);
if (string.IsNullOrEmpty(fname))
{
noFileLst.Add("'" + dr["ctid"].ToString() + "'");
ui += dr["ctid"].ToString() + "未找到附件,";
continue;
}
files.Add(fname);
ctidLst.Add(dr["ctid"].ToString());
fileMd5 += "," + dr["FileMd5"].ToString();
fileNames += Path.GetFileName(fname);
String er = downLoadFiles(userId, dr["ctid"].ToString(), fname, fileNames, seller_memo, ISSF);
if (er.Contains("成功"))
{
copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
}
ui += er + ",";
}
conSuc(ui);
}
else
{
conSuc(ui);
}
}
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 cyt = 0;
if (Request["cyt"] != null)
{
Int32.TryParse(Request["cyt"], out cyt);
}
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,IsSF 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 = "";
String seller_memo = "";
int ISSF = 0;
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 = getDesignDate(dr["FinishDesignTime"]);
string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
if (!Convert.IsDBNull(dr["seller_memo"]))
{
seller_memo = dr["seller_memo"].ToString();
}
if (!Convert.IsDBNull(dr["IsSF"]))
{
ISSF = Convert.ToInt32(dr["IsSF"] == null ? 0 : dr["IsSF"]);
}
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);
if (cyt == 1)
{
downLoadFiles(userId, ctidLst[0], files[0], fileNames, seller_memo, ISSF);
}
}
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("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]);
XLog.SaveLog(userId, files[i] + " is success");
}
}
//public static object downfileObj = new object();
private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
{
XLog.SaveLog(userId, file);
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);
XLog.SaveLog(userId, file + " is success");
}
private String downLoadFiles(int userId, string ctid, string file, String fileNames, String seller_memo, int ISSF)
{
int IsFileEncrypt = IsFileEncrypted(file);
if (IsFileEncrypt == 1 && File.Exists(file))
{
string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
var sb = new StringBuilder(key);
//Linux系统的接口要调用一次,Windows系统要调用两次
CreateUserKey(sb, key.Length);
CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
int result = InitAesKey(sb, sb.Length);
result = IsInitedAesKey();
if (result != 1)
{
addLog(ctid, userId, "初始化秘钥失败" + result, 0);
return ctid + "调用失败";
}
uint a = DecFile(file);
if (a != 0)
{
addLog(ctid, userId, "解密失败" + a, 0);
return ctid + "调用失败";
}
}
int Isshunfen = 2;
int Isjifu = 1;
if (ISSF > 0)
{
Isshunfen = 1;
}
if (ISSF == 2)
{
Isjifu = 0;
}
UpLoadFile uf = new UpLoadFile();
string YEAR = DateTime.Now.Year.ToString();
string MONTH = DateTime.Now.Month.ToString();
string DAY = DateTime.Now.Day.ToString();
string strid = Guid.NewGuid().ToString("N");
string fileExtension = Path.GetExtension(fileNames);//文件格式
string finalfilename = strid + Path.GetExtension(fileNames);// ".cdr";
string onlinepathfilename = "Uploads/temp/" + YEAR + "-" + MONTH + "-" + DAY + "/" + finalfilename;
uf.uploadFilName(file, onlinepathfilename);
string output = fileExtension.Replace(".", ""); // 移除点(.
CeErpTradeCell ce = new CeErpTradeCell();
ce = CeErpTradeCell.GetByCtid(ctid);
if (ce.ReturnReason != "")//打回先取消
{
try
{
cancelOrder(ctid);
}
catch (Exception ex)
{
addLog(ctid, userId, "订单取消失败" + ex.ToString(), 0);
}
}
if (ce.OrderState == 5)
{
JObject jsonObject = new JObject
{
{ "Userid", "77886" },
{ "pwd", "lt666888" },
{ "FileId", strid },
{ "ext", output },
{ "platformorder", ce.tid },//淘宝单号
{ "Filename", fileNames },
{ "Isshunfen", Isshunfen },
{ "Isjifu", Isjifu },
{ "LTOrderId", ce.ctid }
};
string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTInsertNewOrder", jsonObject.ToString());
JObject jsonObjects = JObject.Parse(response);
string msg = (string)jsonObjects["msg"];
if (msg == "插入订单成功")
{
string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 0 + ",'" + msg + "');";
CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
addLog(ctid, userId, "上传彩印通接口成功:" + msg, ce.OrderState);
if (ce != null)
{
ce.FinishPlaceTime = DateTime.Now;
ce.OrderState = 6;
ce.IsReturn = 0;
ce.PlaceUserId = userId;
ce.Update();
CeErpTradeLog logenty = new CeErpTradeLog();
logenty.tid = ctid;
logenty.OrderState = 6;
logenty.UserId = userId;
logenty.OperateTime = DateTime.Now;
logenty.Con = "下载设计文件";
logenty.Create();
}
return ctid + "上传成功";
}
else
{
string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 1 + ",'" + msg + "');";
CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
addLog(ctid, userId, "上传彩印通接口失败:" + msg, ce.OrderState);
XLog.SaveLog(userId, ctid + "订单下单接口调用失败!" + msg);
return ctid + "调用失败";
}
}
return ctid + "调用失败";
}
public static void cancelOrder(string ctid)
{
JObject jsonObject = new JObject
{
{ "Userid", "77886" },
{ "pwd", "lt666888" },
{ "LTOrderId", ctid }
};
string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTCancelOrder", jsonObject.ToString());
}
public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
{
CeErpTradeLog log = new CeErpTradeLog();
log.tid = ctid;
log.UserId = userid;
log.Con = con;
log.OrderState = orderState;
log.AfterSaleState = aftersaleState;
log.OperateTime = DateTime.Now;
log.Create();
}
public static string HttpPost(string url, string param = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Timeout = 120000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="copydownload.aspx.cs" Inherits="copydownload" %>
+365
Näytä tiedosto
@@ -0,0 +1,365 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using SQLData;
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;
using System.Web.UI.WebControls;
public partial class copydownload : System.Web.UI.Page
{
public static string upPath = ConfigurationManager.AppSettings["upPath"];
public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
private void conErc(string msg)
{
Response.Write("{\"type\":\"error\",\"result\":\"" + 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 (Request["hexdata"] != null)
{
string tids = Request["hexdata"];
if (tids.Trim() == "")
{
conErc("无法下载");
return;
}
int userId = 0;
if (Request["userid"] != null)
{
userId = Convert.ToInt32(Request["userid"]);
}
try
{
string[] tArr = tids.Split(',');
List<string> tLst = new List<string>();
foreach (string id in tArr)
{
tLst.Add("'" + id + "'");
}
tids = string.Join(",", tLst.ToArray());
StringBuilder sql = new StringBuilder();
sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName from view_erptradecell where orderstate=5 and ctid in ({0})", tids);
DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
if (dt == null || dt.Rows.Count < 1)
{
conErc("没有找到相关订单");
return;
}
List<string> files = new List<string>();
string dTime = "";
string fname = "";
int fc = 0;
bool hasFile = false;
string df_name = "";
string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
List<string> noFileLst = new List<string>();
List<string> errorFileLst = new List<string>();
foreach (DataRow dr in dt.Rows)
{
if (dr["FinishDesignTime"].ToString() == "") continue;
hasFile = false;
DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
if (ftime.CompareTo(splitTime) > 0)
{
dTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
}
else
dTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
df_name = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]);
foreach (string ext in extArr)
{
fname = df_name + ext;
if (!hasFile)
{
if (File.Exists(fname))
{
bool isCopyError = false;
double payment = 0;
string ctid = dr["ctid"].ToString();
CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
try
{
if (entity != null)
{
payment = entity.payment;
}
hasFile = true;
files.Add(fname);
copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, payment);
fc++;
}
catch (Exception ex)
{
isCopyError = true;
errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
XLog.SaveLog(0, "复制文件发生错误," + fname + "," + ex.Message);
}
//复制完成后修改数据
if (!isCopyError)
{
try
{
if (entity != null)
{
//update ce_erptradecell WITH(ROWLOCK) set FinishPlaceTime = getdate(), OrderState = 6, IsReturn = 0, PlaceUserId = @userid where CHARINDEX(',' + ctid + ',',',' + @mainctids + ',')> 0 and orderstate = 5 and isDianziOrder = 0
//insert into CE_ErpTradeLog(tid, orderstate, userid, operatetime, con) select ctid,6,@userid,getdate(),'下载设计文件' from ce_erptradecell where CHARINDEX(',' + ctid + ',', ',' + @mainctids + ',') > 0
entity.FinishPlaceTime = DateTime.Now;
entity.OrderState = 6;
entity.IsReturn = 0;
entity.PlaceUserId = userId;
entity.Update();
CeErpTradeLog logenty = new CeErpTradeLog();
logenty.tid = ctid;
logenty.OrderState = 6;
logenty.UserId = userId;
logenty.OperateTime = DateTime.Now;
logenty.Con = "下载设计文件";
logenty.Create();
CeErpDataSendOrderInfo.createObject(entity.ctid);
}
SqlParameter[] sqlParameter ={
new SqlParameter("@mainctids", SqlDbType.VarChar,500),
new SqlParameter("@userid", SqlDbType.VarChar,4),
new SqlParameter("@res", SqlDbType.VarChar, 4000)
};
sqlParameter[0].Value = dr["ctid"].ToString();
sqlParameter[1].Value = userId;
sqlParameter[2].Direction = ParameterDirection.Output;
CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
}
catch (Exception ex)
{
errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
XLog.SaveLog(0, "下载发生错误,ctid:" + dr["ctid"].ToString() + "," + ex.Message);
}
}
}
}
else
{
break;
}
}
if (!hasFile)
{
noFileLst.Add("'" + dr["ctid"].ToString() + "'");
//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='{0}' ;", dr["ctid"], (int)OrderState.下单完成, 0, "找不到设计文件");
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
//conErc("找不到文件,订单号:" + dr["ctid"]);
//return;
}
//if (hasFile)
//{
// fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
// if (File.Exists(fname))
// {
// files.Add(fname);
// copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
// }
//}
}
if (fc == 0)
{
conErc("没有找到相关的设计附件");
return;
}
//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}) ;", tids, (int)OrderState.下单完成, userId, "下载设计文件");
//sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
//sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
foreach (string ctid in tArr)
{
CeErpTradeCell.UpdateRelationOrder(ctid);
}
if (Request["supplier"] != null && Request["supplier"].ToString() == "1")
{
ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
}
else if (noFileLst.Count > 0 || errorFileLst.Count > 0)
{
string tips = "";
if (noFileLst.Count > 0)
{
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;
}
if (errorFileLst.Count > 0)
{
string ertids = string.Join(",", errorFileLst.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}) ;", ertids, (int)OrderState., 0, "下载设计文件出错");
CeErpTradeCell.ExecuteNonQuery(sql.ToString());
tips += " 复制下载出错,单号:" + ertids;
}
conErc(tips);
}
else
{
conSuc("文件已下载到共享目录");
}
return;
}
catch (Exception ex)
{
conErc("复制错误的下载访问");
XLog.SaveLog(0, "copydown" + ex.Message);
return;
}
}
}
private string formatMemo(object memo)
{
string m = memo.ToString();
m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
return m;
}
Dictionary<string, string> replaceRules = new Dictionary<string, string>
{
{ "皙贝", "白卡" },
{ "睿狐", "莱尼" },
{ "岚蝶", "安格" },
{ "琮纹", "刚古" },
{ "珠光", "珠光" },
{ "溪雪", "珠光" },
{ "雅柔", "雅柔" },
{ "萱姿", "雅柔" },
{ "草香", "草香" },
{ "芳怡", "草香" },
{ "金绒", "牛皮" },
{ "素芸", "棉卡" },
{ "玉蕊", "蛋壳" }
};
private void copyFile(string date, string supplier, string file, double payment)
{
string SupName = supplier;
if (payment >= 500)
{
SupName = supplier + "500";
}
string path = copyPath + "\\" + date + "\\" + SupName;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
string fname = Path.GetFileName(file);
foreach (var rule in replaceRules)
{
fname = fname.Replace(rule.Key, rule.Value);
}
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(List<string> files, string zipFileName)
{
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();
Page.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
//Response.Flush();
//Response.End();
}
private void downLoadFile(string file)
{
string filePath = Server.MapPath("d/" + file);//路径
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
+18
Näytä tiedosto
@@ -0,0 +1,18 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="downCookie.aspx.cs" Inherits="downCookie" %>
<script type="text/javascript">
window.onload = function () {
// create listener
function receiveMessage(e) {
if (e.data == "cookie") {
parent.postMessage(document.cookie, "*");
} else if (e.data.indexOf("clear")!=-1) {
document.cookie = "fileDownload=; expires=" + new Date(1000).toUTCString() + "; path=" + settings.cookiePath;
}
}
window.addEventListener('message', receiveMessage);
// call parent
//parent.postMessage("GetWhiteLabel", "*");
}
</script>
+17
Näytä tiedosto
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class downCookie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Response.AddHeader("Set-Cookie", "fileDownload=true; path=/; HttpOnly;");
//Page.Response.Flush();
//Page.Response.SuppressContent = true;
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="download.aspx.cs" Inherits="download" %>
+348
Näytä tiedosto
@@ -0,0 +1,348 @@
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);
}
}
+5
Näytä tiedosto
@@ -0,0 +1,5 @@
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": []
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="mulUploadImg.aspx.cs" Inherits="mulUploadImg" %>
+101
Näytä tiedosto
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utils;
using Utils.ImageUtils;
public partial class mulUploadImg : System.Web.UI.Page
{
public static string dPath = ConfigurationManager.AppSettings["dPath"];
private void conSuc(string msg)
{
Response.Write("{\"res\":\"1\",\"msg\":\"" + msg + "\"}");
//Response.End();
}
private void conErc(string msg)
{
Response.Write("{\"res\":\"0\",\"msg\":\"" + msg + "\"}");
//Response.End();
}
public static string GenerateStringID()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count < 1)
{
conErc("空文件!");
return;
}
try
{
string ut = Request.QueryString["ut"];
HttpPostedFile postFile = Request.Files[0];
if (postFile != null)
{
string errMsg = "";
if (ut != "fp")
{
if (!CheckImage(postFile, out errMsg))
{
Response.Write("{\"res\":\"0\",\"msg\":\"不是有效的图片文件!\"}");
Response.End();
return;
}
}
//using (System.Drawing.Image imgThumb = System.Drawing.Image.FromStream(postFile.InputStream))
//{
// result = ImageMaker.ToThumbnailImages(imgThumb, saveFile, 400, "", 9, 3);
//}
string sPath = Path.Combine(dPath, ut);
if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath);
string fName = GenerateStringID() + Path.GetExtension(postFile.FileName);
string saveFile = Path.Combine(sPath, fName);
//上传文件
postFile.SaveAs(saveFile);
//conSuc(fName);
Response.Write("{\"res\":\"1\",\"msg\":\"上传成功!\",\"fn\":\"" + fName + "\"}");
return;
}
}
catch (Exception ex)
{
conErc("发生错误!" + CommonHelper.FormatTextArea(ex.Message));
return;
}
conErc("无法上传");
}
public static bool CheckImage(HttpPostedFile postedFile, out string errMsg)
{
errMsg = "";
if (postedFile == null || postedFile.FileName == "")
{
errMsg = "请选择要上传的图片";
return false;
}
if (postedFile.ContentLength > 83886080)
{
errMsg = "上传的图片大小不允许超过80MB";
return false;
}
return true;
}
}
+7
Näytä tiedosto
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="7z.Libs" version="21.7.0" targetFramework="net48" />
<package id="Squid-Box.SevenZipSharp.Lite" version="1.5.0.366" targetFramework="net48" />
<package id="WindowsAPICodePack-Core" version="1.1.1" targetFramework="net481" />
<package id="WindowsAPICodePack-Shell" version="1.1.1" targetFramework="net481" />
</packages>
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="simUploadFile.aspx.cs" Inherits="simUploadFile" %>
+75
Näytä tiedosto
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utils;
using Utils.ImageUtils;
public partial class simUploadFile : System.Web.UI.Page
{
public static string dPath = ConfigurationManager.AppSettings["dPath"];
private void conSuc(string msg)
{
Response.Write("{\"res\":\"1\",\"msg\":\"" + msg + "\"}");
//Response.End();
}
private void conErc(string msg)
{
Response.Write("{\"res\":\"0\",\"msg\":\"" + msg + "\"}");
//Response.End();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count < 1)
{
conErc("空文件!");
return;
}
try
{
string ut = Request.QueryString["ut"];
HttpPostedFile postFile = Request.Files[0];
if (postFile != null)
{
string errMsg = "";
if (ut != "fp")
{
if (!ImageHandler.CheckImage(postFile, out errMsg))
{
Response.Write("{\"res\":\"0\",\"msg\":\"不是有效的图片文件!\"}");
Response.End();
return;
}
}
//using (System.Drawing.Image imgThumb = System.Drawing.Image.FromStream(postFile.InputStream))
//{
// result = ImageMaker.ToThumbnailImages(imgThumb, saveFile, 400, "", 9, 3);
//}
string strMonth = DateTime.Now.ToString("yyyyMM");
string sPath = Path.Combine(dPath, ut, strMonth);
if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath);
string fName = DateTime.Now.ToFileTime().ToString() + Path.GetExtension(postFile.FileName);
string saveFile = Path.Combine(sPath, fName);
//上传文件
postFile.SaveAs(saveFile);
conSuc(fName);
return;
}
}
catch (Exception ex)
{
conErc("发生错误!" + CommonHelper.FormatTextArea(ex.Message));
return;
}
conErc("无法上传");
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="simdownload.aspx.cs" Inherits="simdownload" %>
+182
Näytä tiedosto
@@ -0,0 +1,182 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class simdownload : System.Web.UI.Page
{
public static string dPath = ConfigurationManager.AppSettings["dPath"];
public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
private void conErc(string msg)
{
Response.Write("{\"type\":\"error\",\"result\":\"" + 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 (Request["hexdata"] != null)
{
string tids = Request["hexdata"];
string fpId = Request["hexdata"];
if (tids.Trim() == "")
{
conErc("无法下载");
return;
}
try
{
string[] tArr = tids.Split(',');
List<string> tLst = new List<string>();
foreach (string id in tArr)
{
tLst.Add("'" + id + "'");
}
tids = string.Join(",", tLst.ToArray());
StringBuilder sql = new StringBuilder();
string ut = Request["ut"];
if (ut == "fp")
{
sql.AppendFormat("select tid,img from ce_erpbill where id=" + fpId );
}
DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
if (dt == null || dt.Rows.Count < 1)
{
conErc("没有找到相关附件");
return;
}
List<string> files = new List<string>();
string dTime = "";
string fname = "";
int fc = 0;
foreach (DataRow dr in dt.Rows)
{
if (dr["img"].ToString() != "")
{
if(!File.Exists(dPath + "\\" + ut + "\\" + dr["img"].ToString()))
{
conErc("找不到文件:"+ dr["img"].ToString());
return;
}
files.Add(dPath + "\\" + ut + "\\" + dr["img"].ToString());
}
}
if (files.Count < 1)
{
conErc("没有找到相关附件");
return;
}
if(files.Count==1)downLoadFile(files[0]);
else
{
ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
}
return;
}
catch (Exception ex)
{
conErc("错误的下载访问" + tids + "," + 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);
}
private string getDesignTime(object v)
{
if (v.ToString()=="") return "";
return Convert.ToDateTime(v).ToString("yyyyMM");
}
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(List<string> files, string zipFileName)
{
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();
Page.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
//Response.Flush();
//Response.End();
}
private void downLoadFile(string file)
{
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.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
//Response.Flush();
Response.End();
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="supplierDownload.aspx.cs" Inherits="supplierDownload" %>
+410
Näytä tiedosto
@@ -0,0 +1,410 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using NPOI.OpenXmlFormats.Dml.Diagram;
using NPOI.OpenXmlFormats.Shared;
using SiteCore.Handler;
using SiteCore.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Services.Description;
using System.Web.UI;
public partial class supplierDownload : 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"];
[DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
public static extern uint DecFile(string filename);
[DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
[DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
public static extern void CreateUserKey(StringBuilder key, int len);
[DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
public static extern int InitAesKey(StringBuilder key, int len);
[DllImport("DrvInterface64.dll")]
public static extern int IsInitedAesKey();
private void conErc(string msg)
{
XLog.SaveLog(0, msg);
Response.Write(msg);
//Response.StatusCode = (int)HttpStatusCode.NotFound;
//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 = getDesignTime(dr["FinishDesignTime"]);
string ctid = dr["ctid"].ToString();
string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
string fname = getCanDownFile(df_name);
int IsFileEncrypt = IsFileEncrypted(fname);
if (IsFileEncrypt == 1 && File.Exists(fname))
{
string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
var sb = new StringBuilder(key);
//Linux系统的接口要调用一次,Windows系统要调用两次
CreateUserKey(sb, key.Length);
CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
int result = InitAesKey(sb, sb.Length);
result = IsInitedAesKey();
if (result != 1)
{
addLog(ctid, userId, "初始化秘钥失败" + result, 0);
noFileLst.Add("'" + ctid + "'");
continue;
}
uint a = DecFile(fname);
if (a != 0)
{
addLog(ctid, userId, "解密失败" + a, 0);
noFileLst.Add("'" + ctid + "'");
continue;
}
}
if (string.IsNullOrEmpty(fname))
{
noFileLst.Add("'" + ctid + "'");
continue;
}
files.Add(fname);
ctidLst.Add(ctid);
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);
XLog.SaveLog(0, "download" + 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("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;
List<string> addFiles = new List<string>();
List<string> addCtid = new List<string>();
using (ZipFile file = ZipFile.Create(ms))
{
file.BeginUpdate();
//file.NameTransform = new ZipNameTransform();
file.NameTransform = new MyNameTransfom();
for (int i = 0; i < ctidLst.Count; i++)
{
if (File.Exists(files[i]))
{
try
{
file.Add(files[i]);
addFiles.Add(files[i]);
addCtid.Add(ctidLst[i]);
}
catch (Exception ex)
{
}
}
}
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("Access-Control-Expose-Headers", "Content-Disposition");
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
Response.AddHeader("Content-Length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
Page.Response.Flush();
//for (int i = 0; i < addFiles.Count; i++)
//{
// updateIsDownSuccess(userId, addCtid[i]);
//}
//StringBuilder sql = new StringBuilder();
//string tids = string.Join(",", addCtid);
//sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
//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}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
}
//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.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
Response.BinaryWrite(bytes);
Response.Flush();
//updateIsDownSuccess(userId, ctid);
//StringBuilder sql = new StringBuilder();
//string tids = string.Join(",", ctid);
//sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
//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}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
}
public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
{
CeErpTradeLog log = new CeErpTradeLog();
log.tid = ctid;
log.UserId = userid;
log.Con = con;
log.OrderState = orderState;
log.AfterSaleState = aftersaleState;
log.OperateTime = DateTime.Now;
log.Create();
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testcopydownload.aspx.cs" Inherits="testcopydownload" %>
+295
Näytä tiedosto
@@ -0,0 +1,295 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using SQLData;
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;
using System.Web.UI.WebControls;
public partial class testcopydownload : System.Web.UI.Page
{
public static string upPath = ConfigurationManager.AppSettings["upPath"];
public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
private void conErc(string msg)
{
Response.Write("{\"type\":\"error\",\"result\":\"" + 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 (Request["hexdata"]!=null)
{
string tids = Request["hexdata"];
if (tids.Trim() == "")
{
conErc("无法下载");
return;
}
int userId = 0;
if (Request["userid"] != null)
{
userId = Convert.ToInt32(Request["userid"]);
}
try
{
string[] tArr = tids.Split(',');
List<string> tLst = new List<string>();
foreach (string id in tArr)
{
tLst.Add("'" + id + "'");
}
tids = string.Join(",", tLst.ToArray());
StringBuilder sql = new StringBuilder();
sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName from view_erptradecell where orderstate=5 and ctid in ({0})", tids);
DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
if (dt == null || dt.Rows.Count < 1)
{
conErc("没有找到相关订单");
return;
}
List<string> files = new List<string>();
string dTime = "";
string fname = "";
int fc = 0;
bool hasFile = false;
string df_name = "";
string[] extArr = new string[] { ".cdr", ".zip",".rar" };
List<string> noFileLst = new List<string>();
List<string> errorFileLst = new List<string>();
foreach (DataRow dr in dt.Rows)
{
if (dr["FinishDesignTime"].ToString() == "") continue;
hasFile = false;
dTime = getDesignTime(dr["FinishDesignTime"]);
df_name = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]);
foreach (string ext in extArr)
{
fname = df_name + ext;
if (!hasFile)
{
if (File.Exists(fname))
{
//bool isUpdateError = false;
//try
//{
// SqlParameter[] sqlParameter ={
// new SqlParameter("@mainctids", SqlDbType.VarChar,500),
// new SqlParameter("@userid", SqlDbType.VarChar,4),
// new SqlParameter("@res", SqlDbType.VarChar, 4000)
// };
// sqlParameter[0].Value = dr["ctid"].ToString();
// sqlParameter[1].Value = userId;
// sqlParameter[2].Direction = ParameterDirection.Output;
// CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
//}
//catch (Exception ex)
//{
// isUpdateError = true;
// errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
// XLog.SaveLog(0, "下载发生错误,ctid:" + dr["ctid"].ToString() + "," + ex.Message);
//}
//if (!isUpdateError)
//{
hasFile = true;
files.Add(fname);
copyFile( fname);
fc++;
//}
}
}
else
{
break;
}
}
if (!hasFile)
{
noFileLst.Add("'" + dr["ctid"].ToString() + "'");
//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='{0}' ;", dr["ctid"], (int)OrderState.下单完成, 0, "找不到设计文件");
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
//conErc("找不到文件,订单号:" + dr["ctid"]);
//return;
}
//if (hasFile)
//{
// fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
// if (File.Exists(fname))
// {
// files.Add(fname);
// copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
// }
//}
}
if (fc == 0)
{
conErc("没有找到相关的设计附件");
return;
}
//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}) ;", tids, (int)OrderState.下单完成, userId, "下载设计文件");
//sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
//sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
foreach (string ctid in tArr)
{
CeErpTradeCell.UpdateRelationOrder(ctid);
}
if (Request["supplier"] != null && Request["supplier"].ToString() == "1")
{
ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
}
else if (noFileLst.Count > 0 || errorFileLst.Count > 0)
{
string tips = "";
if (noFileLst.Count > 0)
{
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;
}
if (errorFileLst.Count > 0)
{
string ertids = string.Join(",", errorFileLst.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}) ;", ertids, (int)OrderState.下单完成, 0, "下载设计文件出错");
//CeErpTradeCell.ExecuteNonQuery(sql.ToString());
tips += " 下载出错,单号:" + ertids;
}
conErc(tips);
}
else
{
conSuc("文件已下载到共享目录");
}
return;
}
catch(Exception ex)
{
conErc("错误的下载访问");
XLog.SaveLog(0, "copydown"+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 file)
{
try
{
string path = copyPath + "\\" + "testcopy" ;
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);
//}
}
catch(Exception ex)
{
XLog.SaveLog(0, "复制文件发生错误," + file + "," + ex.Message);
}
}
private string getDesignTime(object v)
{
if (v.ToString()=="") return "";
return Convert.ToDateTime(v).ToString("yyyyMM");
}
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(List<string> files, string zipFileName)
{
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();
Page.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
//Response.Flush();
//Response.End();
}
private void downLoadFile(string file)
{
string filePath = Server.MapPath("d/"+file);//路径
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
+2
Näytä tiedosto
@@ -0,0 +1,2 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadFile.aspx.cs" Inherits="uploadFile" %>
+704
Näytä tiedosto
@@ -0,0 +1,704 @@
using BizCom;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;
using SevenZip;
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;
using Utils;
using SiteCore;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging;
using Microsoft.WindowsAPICodePack.Shell;
using System.Drawing.Imaging;
using CorelDRAW;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Data;
public partial class uploadFile : System.Web.UI.Page
{
public static string upPath = ConfigurationManager.AppSettings["upPath"];
public static string curPath = ConfigurationManager.AppSettings["curPath"];
static CdrConvert cdrConvert = new CdrConvert();
private void conSuc(string msg)
{
Response.Write("{\"res\":\"1\",\"msg\":\"" + msg + "!\"}");
//Response.End();
}
private void conErc(string msg)
{
Response.Write("{\"res\":\"0\",\"msg\":\"" + msg + "!\"}");
//Response.End();
}
public string GetMD5HashFromFile(HttpPostedFile file)
{
try
{
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file.InputStream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
XLog.SaveLog(0, "上传MD5错误!" + ex.Message);
}
return "";
}
private static byte[] GetBlobByHttpPostedFile(HttpPostedFile httpPostedFile)
{
var contentLength = httpPostedFile.ContentLength;
var result = new byte[contentLength];
var inputStream = httpPostedFile.InputStream;
inputStream.Read(result, 0, contentLength);
return result;
}
protected void Page_Load(object sender, EventArgs e)
{
//if (CurrentUser == null)
//{
// Response.Write(err);
// return;
//}
//CeErpTradeCell.GetByCtid("1717009344450030601");
if (Request.Files.Count < 1)
{
conErc("空文件!");
return;
}
int userId = 0;
int orgid = 0;
if (Request["userid"] != null)
{
userId = Convert.ToInt32(Request["userid"]);
}
if (Request["orgid"] != null)
{
orgid = Convert.ToInt32(Request["orgid"]);
}
HttpPostedFile postFile = Request.Files[0];
if (postFile != null)
{
string file_name = postFile.FileName;
string namePattern = @"《(.*?)》";
Regex nameReg = new Regex(namePattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
MatchCollection nameMatches = nameReg.Matches(file_name);//设定要查找的字符串
if (nameMatches.Count > 0)
{
foreach (Match match in nameMatches)
{
file_name = file_name.Replace(match.Value, "");
}
}
file_name = file_name.Replace("", "(");
file_name = file_name.Replace("", ")");
string ctid = MidStrEx(file_name, "(", ")").Trim();
if (string.IsNullOrEmpty(ctid))
{
conErc("上传的文件名格式不正确");
return;
}
string memoCtid = ctid;
if (ctid.IndexOf("C") == -1)
{
if (file_name.IndexOf("[") != -1 && file_name.IndexOf("C") != -1)
{
if (ctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1] 对应ctid是 S_S_C1_1962772776865084101
{
int lastIndex = ctid.LastIndexOf("S_"); //最后一个S_的位置
string sPre = ctid.Substring(0, lastIndex + 2); //S_S_
string initTid = ctid.Substring(lastIndex + 2, ctid.Length - lastIndex - 2); //1962772776865084101
string pre_ctid = MidStrEx(file_name, "[", "]"); //C1
if (pre_ctid.IndexOf("+") != -1)
{
pre_ctid = "C" + pre_ctid.Split('+')[1];
}
memoCtid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101
}
else
{
string pre_ctid = MidStrEx(file_name, "[", "]");
if (pre_ctid.IndexOf("+") != -1)
{
pre_ctid = "C" + pre_ctid.Split('+')[1];
}
memoCtid = pre_ctid + "_" + ctid;
}
}
}
CeErpTradeCell entity = null;
if (ctid != "") entity = CeErpTradeCell.GetByCode(ctid);
if (entity == null) entity = CeErpTradeCell.GetByCtid(ctid);
if (entity == null) entity = CeErpTradeCell.GetByCtid(memoCtid);
try
{
if (entity != null)
{
string pname = Path.GetFileNameWithoutExtension(file_name);
if (entity.IsRefund == 2)
{
StringBuilder sql = new StringBuilder();
sql.AppendFormat("select refund_status from CE_ErpTradeOrder where tid='{0}'", entity.tid);
DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
bool isAll = true;
foreach (DataRow dr in dt.Rows)
{
if ("NO_REFUND".Equals(dr["refund_status"]))
{
isAll = false;
break;
}
}
if (isAll)
{
conErc("此单退款,不允许上传");
return;
}
}
if (entity.seller_memo != pname)
{
conErc("上传的文件名与备注不符合!");
return;
}
if (entity.OrderState == -1)
{
conErc("还未审核不允许上传");
return;
}
if (entity.OrderState < (int)OrderState. && orgid != 10 && orgid != 4)
{
conErc("还未开始设计不允许上传");
return;
}
//if (pname.IndexOf("现货") != -1)
//{
// conErc("设计款的单文件名不能有现货字眼");
// return;
//}
//更新状态
if (entity.OrderState >= (int)OrderState.)
{
conErc("已经下单无法上传!");
return;
}
string extend = Path.GetExtension(file_name).ToLower();
if (!(extend == ".cdr" || extend == ".zip" || extend == ".rar" || extend == ".pdf"))
{
conErc("只允许上传zip和cdr文件!");
return;
}
if (entity.OrderState != 5)
{
entity.FinishDesignTime = DateTime.Now;
if (entity.isDianziOrder == 1 || entity.ProductId == 57 || entity.ProductId == 28)
{
entity.OrderState = 7;
commonHelper.setOrderDummyDelivery(entity.tid);
}
else
entity.OrderState = 5; //设计完成
//if (entity.IsReturn == 2) //2是下单人打回给设计的,重新上传的话,需要清除打回
//{
entity.IsReturn = 0;
entity.IsXianHuo = 0;
entity.IsVerifyToSupplier = false;
//}
}
if (entity.MemoOpt == 1 || entity.MemoOpt == 2)
{
entity.MemoOpt = 0;
}
if (entity.payment < 500)
{
if (entity.seller_memo.Contains("插卡") && entity.ProductCount != null && !entity.seller_memo.Contains("S_"))
{
int num = 0;
try
{
string text = entity.ProductCount;
string pattern = @"(\d+)\s*张";
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches)
{
if (match.Success)
{
num = Convert.ToInt32(match.Groups[1].Value);
break;
}
}
}
catch (Exception ex)
{
}
if (num >= 100)
{
entity.IsVerifyToSupplier = true;
entity.SupplierId = 3;
entity.FinishPlaceTime = DateTime.Now;
}
}
if (((entity.seller_memo.Contains("条幅彩色") && !entity.seller_memo.Contains("辽宁") && !entity.seller_memo.Contains("山东")) || entity.seller_memo.Contains("贡锻布") || entity.seller_memo.Contains("贡缎布")) && !entity.seller_memo.Contains("双喷"))
{
entity.IsVerifyToSupplier = true;
entity.SupplierId = 98;
entity.FinishPlaceTime = DateTime.Now;
}
}
string dPath = entity.FinishDesignTime.GetValueOrDefault().ToString("yyyyMMdd");
//XLog.SaveLog(5, dPath);
string sPath = Path.Combine(upPath, dPath);
string cpath = Path.Combine(upPath, entity.FinishDesignTime.GetValueOrDefault().ToString("yyyyMM"));
//XLog.SaveLog(5, sPath);
//XLog.SaveLog(5, Directory.Exists(sPath).ToString());
if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath);
if (!Directory.Exists(cpath)) Directory.CreateDirectory(cpath);
string saveFile = Path.Combine(sPath, file_name);
string f_ext = Path.GetExtension(saveFile);
string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
string _file = "";
foreach (string ext in extArr)
{
if (f_ext != ext)
{
_file = saveFile.Replace(f_ext, ext);
if (File.Exists(_file)) File.Delete(_file);
}
else
{
if (File.Exists(saveFile)) File.Delete(saveFile);
}
}
//上传文件
postFile.SaveAs(saveFile);
entity.FileMd5 = GetMD5HashFromFile(postFile);
//XLog.SaveLog(0, saveFile);
entity.Update();
//CeErpTradeCell.UpdateRelationOrder(entity);
CeErpTradeCell.UpdateRelationOrder(entity.ctid);
CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, userId, "上传设计文件-" + saveFile);
if (Path.GetExtension(saveFile).IndexOf("cdr", StringComparison.OrdinalIgnoreCase) != -1)
{
//string sql = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", saveFile);
//CeErpTradeLog.ExecuteNonQuery(sql);
}
else if (Path.GetExtension(saveFile).IndexOf("zip", StringComparison.OrdinalIgnoreCase) != -1 || Path.GetExtension(saveFile).IndexOf("rar", StringComparison.OrdinalIgnoreCase) != -1)
{
try
{
DecompressZIPandRAR(saveFile, sPath, file_name);
}
catch (Exception ex)
{
CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, entity.DesignUserId, "解压失败!");
XLog.SaveLog(0, "上传解压发生错误!" + ex.Message);
}
//Decompress(saveFile,sPath);
}
//new Thread(new ThreadStart(delegate ()
//{
//System.Threading.Thread.Sleep(2000);
if (Path.GetExtension(saveFile).IndexOf("cdr", StringComparison.OrdinalIgnoreCase) != -1)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
writeLog("上传完成!" + saveFile);
Task.Run(async () =>
{
string filePath = Path.GetFullPath(saveFile);
string targPath = Path.Combine(cpath, file_name);
using (identity.Impersonate())
{
try
{
if (File.Exists(filePath))
{
cdrConvert.CdrConvertPng(filePath, targPath);
}
}
catch (Exception ex)
{
XLog.SaveLog(0, filePath + ",转成图片出错:" + ex.Message);
}
}
});
}
//})).Start();
conSuc("上传成功!");
return;
}
else
{
conErc("找不到对应的订单");
return;
}
}
catch (Exception ex)
{
conErc("上传发生错误!" + CommonHelper.FormatTextArea(ex.Message));
CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, entity.DesignUserId, "上传失败!");
XLog.SaveLog(0, "上传发生错误!" + ex.Message);
return;
}
finally
{
if (postFile != null)
{
postFile.InputStream.Close();
}
}
}
conErc("空文件!");
}
class CdrConvert
{
private object lockObject = new object();
public void CdrConvertPng(string filePath, string targPath)
{
lock (lockObject)
{
writeLog("开始截图!" + filePath);
targPath = targPath.Replace(".cdr", ".png");
try
{
Application cdr = new Application();
cdr.OpenDocument(filePath, 1);
cdr.ActiveDocument.ExportBitmap(
targPath,
cdrFilter.cdrPNG,
cdrExportRange.cdrCurrentPage,
cdrImageType.cdrRGBColorImage,
0, 0, 72, 72,
cdrAntiAliasingType.cdrNoAntiAliasing,
false,
true,
true,
false,
cdrCompressionType.cdrCompressionNone,
null).Finish();
cdr.ActiveDocument.Close();
cdr.Quit();
cdr = null;
}
catch (Exception ex)
{
XLog.SaveLog(0, targPath + ",转成图片出错:" + ex.Message);
}
finally
{
KillProcessByName("CorelDRW");
}
}
}
void KillProcessByName(string processName)
{
Process[] processes = Process.GetProcessesByName(processName);
foreach (Process process in processes)
{
try
{
process.Kill();
process.WaitForExit(); // 等待进程退出
}
catch (Exception ex)
{
}
}
}
}
private void DecompressZIPandRAR(string zipFile, string targetPath, string filename)
{
string notExtension = filename.Substring(0, filename.Length - 4);
SevenZipExtractor.SetLibraryPath(Server.MapPath("bin\\7z.dll"));
LibraryFeature lf = SevenZipExtractor.CurrentLibraryFeatures;
using (SevenZipExtractor szExtra = new SevenZipExtractor(zipFile))
{
//szExtra.ExtractArchive("d:\\temp");
foreach (string afn in szExtra.ArchiveFileNames)
{
if (afn.IndexOf(notExtension, StringComparison.OrdinalIgnoreCase) != -1)
{
szExtra.ExtractFiles(targetPath, afn);
break;
}
}
}
}
private void Decompress(string GzipFile, string targetPath)
{
//string directoryName = Path.GetDirectoryName(targetPath + "\\") + "\\";
string directoryName = targetPath + "\\";
if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录
//helper.writeLog(GzipFile);
//helper.writeLog(directoryName);
string CurrentDirectory = directoryName;
byte[] data = new byte[2048];
int size = 2048;
ZipEntry theEntry = null;
Stream _stream = File.OpenRead(GzipFile);
if (_stream.Length == 0) { _stream.Close(); return; }
try
{
using (ZipInputStream s = new ZipInputStream(_stream))
{
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{// 该结点是目录
if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
}
else
{
if (theEntry.Name != String.Empty && (theEntry.Name.IndexOf(".png", StringComparison.OrdinalIgnoreCase) != -1 || theEntry.Name.IndexOf(".jpg", StringComparison.OrdinalIgnoreCase) != -1))
{
//解压文件到指定的目录
using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
{
while (true)
{
size = s.Read(data, 0, data.Length);
if (size <= 0) break;
streamWriter.Write(data, 0, size);
}
streamWriter.Close();
}
break;
}
}
}
s.Close();
}
}
catch (Exception ex)
{
XLog.SaveLog(0, "解压uncau:" + ex.Message);
}
}
public string unCompressRAR(string unRarPatch, string rarPatch, string rarName)
{
string the_rar;
RegistryKey the_Reg;
object the_Obj;
string the_Info;
try
{
the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
if (Directory.Exists(unRarPatch) == false)
{
Directory.CreateDirectory(unRarPatch);
}
the_Info = "x " + rarName + " " + unRarPatch + " -y";
ProcessStartInfo the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_StartInfo.WorkingDirectory = rarPatch;//获取压缩包路径
Process the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
the_Process.WaitForExit();
the_Process.Close();
}
catch (Exception ex)
{
throw ex;
}
return unRarPatch;
}
private void ShellCdrConvertPng(string path, string targPath)
{
ShellFile shellFile = ShellFile.FromFilePath(path);
System.Drawing.Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
//在画板的指定位置画图
targPath = targPath.Replace(".cdr", ".png");
shellThumb.Save(targPath, ImageFormat.Png);
shellThumb.Dispose();
shellFile.Dispose();
}
private void CdrConvertPng(string path, string targPath)
{
using (Aspose.Imaging.FileFormats.Cdr.CdrImage image = (Aspose.Imaging.FileFormats.Cdr.CdrImage)Aspose.Imaging.Image.Load(path))
{
PngOptions options = new Aspose.Imaging.ImageOptions.PngOptions();
options.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;
// Set rasterization options for fileformat
options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)
image.GetDefaultOptions(new object[] { Aspose.Imaging.Color.White, image.Width, image.Height });
options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
options.VectorRasterizationOptions.SmoothingMode = Aspose.Imaging.SmoothingMode.None;
targPath = targPath.Replace(".cdr", ".png");
image.Save(targPath, options);
options.Dispose();
}
}
private string CdrExPng(string path, string targPath)
{
try
{
targPath = targPath.Replace(".cdr", ".png");
Application cdr = new Application();
cdr.OpenDocument(path, 1);
cdr.ActiveDocument.ExportBitmap(
targPath,
cdrFilter.cdrPNG,
cdrExportRange.cdrCurrentPage,
cdrImageType.cdrRGBColorImage,
0, 0, 72, 72,
cdrAntiAliasingType.cdrNoAntiAliasing,
false,
true,
true,
false,
cdrCompressionType.cdrCompressionNone,
null).Finish();
cdr.ActiveDocument.Close();
cdr.Quit();
cdr = null;
GC.Collect();
}
catch (Exception ex)
{
XLog.SaveLog(0, path + ",转成图片出错:" + ex.Message);
}
finally
{
}
return "111";
}
private static object cdrpngobj = new object();
private void CdrExportPng(string path, string cdrFile)
{
lock (cdrpngobj)
{
string fname = curPath + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png";
string new_fname = path + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png";
CorelDRAW.Application cdr = new CorelDRAW.Application();
cdr.OpenDocument(cdrFile, 1);
cdr.ActiveDocument.ExportBitmap(
fname,
CorelDRAW.cdrFilter.cdrPNG,
CorelDRAW.cdrExportRange.cdrCurrentPage,
CorelDRAW.cdrImageType.cdrRGBColorImage,
0, 0, 72, 72,
CorelDRAW.cdrAntiAliasingType.cdrNoAntiAliasing,
false,
true,
true,
false,
CorelDRAW.cdrCompressionType.cdrCompressionNone,
null).Finish();
cdr.ActiveDocument.Close();
cdr.Quit();
if (File.Exists(fname))
{
File.Copy(fname, new_fname);
File.Delete(fname);
}
}
}
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
Console.WriteLine("MidStrEx Err:" + ex.Message);
}
return result;
}
private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
private static object logFlag = new object();
public static void writeLog(string log)
{
lock (logFlag)
{
using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
{
sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
sw.Flush();
}
}
}
}
}
+1
Näytä tiedosto
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadImg.aspx.cs" Inherits="uploadImg" %>
+73
Näytä tiedosto
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utils;
using Utils.ImageUtils;
public partial class uploadImg : System.Web.UI.Page
{
public static string dPath = ConfigurationManager.AppSettings["dPath"];
private void conSuc(string msg)
{
Response.Write("{\"res\":\"1\",\"msg\":\"" + msg + "\"}");
//Response.End();
}
private void conErc(string msg)
{
Response.Write("{\"res\":\"0\",\"msg\":\"" + msg + "\"}");
//Response.End();
}
protected void Page_Load(object sender, EventArgs e)
{
string err = "{\"res\":\"0\",\"msg\":\"上传失败!\"}";
//if (CurrentUser==null)
//{
// Response.Write(err);
// return;
//}
if (Request.Files.Count < 1)
{
Response.Write(err);
return;
}
string idx = Request.QueryString["idx"];
if (idx == "")
{
Response.Write(err);
return;
}
//string fn = DateTime.Now.ToString("yyyyMMddHHmmss");
string ut = Request.QueryString["ut"];
try
{
HttpPostedFile postFile = Request.Files[0];
if (postFile != null)
{
string errMsg = "";
if (!ImageHandler.CheckImage(postFile, out errMsg)) return;
string sPath = Path.Combine(dPath, ut);
string fileName = postFile.FileName;
string saveFile = Path.Combine(sPath, fileName);
string result = "";
using (System.Drawing.Image imgThumb = System.Drawing.Image.FromStream(postFile.InputStream))
{
result = ImageMaker.ToThumbnailImages(imgThumb, saveFile, 800, "", 9, 3);
}
Response.Write("{\"res\":\"1\",\"msg\":\"上传成功!\",\"ridx\":\"" + idx + "\",\"fn\":\"" + SecurityHelper.EncodingBase64(fileName) + "\"}");
return;
}
}
catch(Exception ex)
{
Response.Write(err+ex.Message);
}
Response.Write(err);
}
}
+11
Näytä tiedosto
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<!--
Visual Studio global web project settings.
-->
<VisualWebDeveloper>
<comReferences>
<reference Name="interop.coreldraw" ID="{FBF4300F-D921-11D1-B806-00A0C90646A9}\14.0\0"/>
<reference Name="interop.vgcore" ID="{95E23C91-BC5A-49F3-8CD1-1FC515597048}\14.0\0"/>
</comReferences>
</VisualWebDeveloper>
+47
Näytä tiedosto
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
***********************************************************************************************
website.publishproj
警告: 请勿修改此文件,它将用于 Web 发布过程。
版权所有 (C) Microsoft Corporation。保留所有权利。
***********************************************************************************************
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.30319</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{a804226a-ae92-41fa-ac2c-ae69ba8a42f5}</ProjectGuid>
<SourceWebPhysicalPath>$(MSBuildThisFileDirectory)</SourceWebPhysicalPath>
<SourceWebVirtualPath>/UploadWeb</SourceWebVirtualPath>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<SourceWebProject>
</SourceWebProject>
<SourceWebMetabasePath>
</SourceWebMetabasePath>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<!-- for VS2010 we need to use 10.5 but for VS2012+ we should use VisualStudioVersion -->
<WebPublishTargetsVersion Condition=" '$(WebPublishTargetsVersion)' =='' and '$(VisualStudioVersion)' == 10.0 ">10.5</WebPublishTargetsVersion>
<WebPublishTargetsVersion Condition=" '$(WebPublishTargetsVersion)'=='' ">$(VisualStudioVersion)</WebPublishTargetsVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(WebPublishTargetsVersion)</VSToolsPath>
<_WebPublishTargetsPath Condition=" '$(_WebPublishTargetsPath)'=='' ">$(VSToolsPath)</_WebPublishTargetsPath>
<AssemblyFileVersion Condition="'$(AssemblyFileVersion)' == ''">1.0.0.0</AssemblyFileVersion>
<AssemblyVersion Condition="'$(AssemblyVersion)' == ''">1.0.0.0</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<AssemblyAttributes Include="AssemblyFileVersion">
<Value>$(AssemblyFileVersion)</Value>
</AssemblyAttributes>
<AssemblyAttributes Include="AssemblyVersion">
<Value>$(AssemblyVersion)</Value>
</AssemblyAttributes>
</ItemGroup>
<Import Project="$(_WebPublishTargetsPath)\Web\Microsoft.WebSite.Publishing.targets" />
</Project>