Files
lserp_cs_6.0/插件库/Lskj.Util/UploadFileUtil.cs
T
tdx 809d3df242 SVN r1160
SVN-Revision: r1160
2026-04-23 09:09:45 +00:00

304 lines
12 KiB
C#

using Lskj.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace Lskj.Util
{
public static class UploadFileUtil
{
/// <summary>
/// 登录获取token
/// </summary>
/// <param name="oaUrl"></param>
/// <returns></returns>
public static string Login(string oaUrl)
{
string token = "";
try
{
string loginUrl = $"{oaUrl}/Api/SysUserAjaxApi.ashx";
HttpHelper.Setting("application/x-www-form-urlencoded", null, null, HttpHelper.Encode.UTF8);
Dictionary<string, string> loginPmsDic = new Dictionary<string, string>();
loginPmsDic.Add("method", "Login");
loginPmsDic.Add("username", HttpUtility.UrlEncode(ERPInfo.Instance.UserName));
loginPmsDic.Add("password", HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord));
HttpWebResponse loginResponse = HttpHelper.Post(loginUrl, "", loginPmsDic, null, out string loginResult);
if (loginResponse != null && !string.IsNullOrEmpty(loginResult))
{
JObject jObject = JsonConvert.DeserializeObject<JObject>(loginResult);
if (jObject.ContainsKey("success"))
{
if ((jObject["success"] + "").Equals("True"))
{
if (jObject.ContainsKey("token"))
{
token = jObject["token"] + "";
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return token;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="token"></param>
/// <param name="url"></param>
/// <param name="fileStream"></param>
/// <param name="fileId"></param>
/// <param name="returnMsg"></param>
/// <returns></returns>
public static bool UploadFile(string token, string url, string fileStream, out string fileId, out string returnMsg)
{
bool isUpload = false;
fileId = "-1";
returnMsg = "";
if (!string.IsNullOrEmpty(token))
{
HttpHelper.Setting("application/x-www-form-urlencoded", null, null);
string result = "";
Dictionary<string, string> headerDic = new Dictionary<string, string>();
headerDic.Add("Authorization", $"Bearer {token}");
HttpWebResponse webResponse = HttpHelper.Post(url, fileStream, null, headerDic, out result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject jsonObject = (JObject)JsonConvert.DeserializeObject(result);
string isSuccess = jsonObject["success"] + "";
if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase))
{
if (jsonObject.ContainsKey("other"))
{
fileId = jsonObject["other"] + "";
}
isUpload = true;
}
else
{
if (jsonObject.ContainsKey("msg"))
{
returnMsg = jsonObject["msg"] + "";
}
isUpload = false;
}
}
else
{
returnMsg = "上传请求失败";
isUpload = false;
}
}
else
{
returnMsg = "登录失败";
isUpload = false;
}
return isUpload;
}
public static bool UploadFile(string token, string postUrl, string filePath, string moduleCode, string idValue, string speciesno, out string fileId, out string rtnMsg)
{
bool isUpload = false;
fileId = "";
rtnMsg = "";
try
{
FileInfo fileInfo = new FileInfo(filePath);
int pageSize = 1 * 1024 * 1024;
long totalSize = fileInfo.Length;
long position = 0;
int comfirm = 0;
int encode = 4;
int failNum = 0;
bool hasFail = false;
string uploadToken = Guid.NewGuid().ToString("N").Substring(0, 24);
string uploadFileName = Path.GetFileName(filePath);
// 如果你后台没有 DoWebUploadSafe,就改回 DoWebUpload
string uploadMethod = "DoWebUpload";
Dictionary<string, string> headerDic = new Dictionary<string, string>();
headerDic.Add("Authorization", "Bearer " + token);
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
while (position < totalSize)
{
int readSize = (int)Math.Min(pageSize, totalSize - position);
byte[] buffer = new byte[readSize];
int realRead = fs.Read(buffer, 0, readSize);
if (realRead <= 0)
{
break;
}
if (realRead != readSize)
{
byte[] tempBytes = new byte[realRead];
Array.Copy(buffer, tempBytes, realRead);
buffer = tempBytes;
readSize = realRead;
}
long tsp = GetUnixTime();
string uploadUrl = string.Format(
postUrl,
moduleCode,
HttpUtility.UrlEncode(idValue),
"file",
totalSize,
position,
HttpUtility.UrlEncode(uploadFileName),
uploadMethod,
HttpUtility.UrlEncode(speciesno),
comfirm,
encode,
uploadToken,
tsp
);
string result = "";
HttpWebResponse webResponse = HttpHelper.PostFileChunk(uploadUrl, buffer, uploadFileName, headerDic, out result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject jsonObject = (JObject)JsonConvert.DeserializeObject(result);
string isSuccess = jsonObject["success"] + "";
if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase))
{
failNum = 0;
if (jsonObject.ContainsKey("data") && jsonObject["data"] != null && jsonObject["data"].Type == JTokenType.Object)
{
JObject dataObject = (JObject)jsonObject["data"];
if (dataObject.ContainsKey("FileName"))
{
uploadFileName = dataObject["FileName"] + "";
}
}
if (jsonObject.ContainsKey("other"))
{
fileId = jsonObject["other"] + "";
}
position += readSize;
}
else
{
string dataCode = jsonObject.ContainsKey("data") ? jsonObject["data"] + "" : "";
if (dataCode.Equals("9") && comfirm == 0)
{
comfirm = 1;
fs.Position = position;
continue;
}
if (jsonObject.ContainsKey("msg"))
{
rtnMsg = jsonObject["msg"] + "";
}
failNum++;
if (failNum < 2 && rtnMsg.IndexOf("权限") < 0 && rtnMsg.IndexOf("禁止") < 0)
{
fs.Position = position;
continue;
}
hasFail = true;
break;
}
}
else
{
rtnMsg = "上传请求失败," + result;
hasFail = true;
break;
}
}
}
if (!hasFail && position >= totalSize)
{
isUpload = true;
}
}
catch (Exception ex)
{
rtnMsg = ex.Message;
isUpload = false;
}
return isUpload;
}
private static long GetUnixTime()
{
DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return (long)(DateTime.UtcNow - startTime).TotalSeconds;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="token"></param>
/// <param name="url"></param>
/// <param name="returnMsg"></param>
/// <returns></returns>
public static bool DeleteFile(string token, string url, out string returnMsg)
{
bool isDelete = false;
returnMsg = "";
if (!string.IsNullOrEmpty(token))
{
HttpHelper.Setting("application/x-www-form-urlencoded", null, null);
Dictionary<string, string> headerDic = new Dictionary<string, string>();
headerDic.Add("Authorization", $"Bearer {token}");
HttpWebResponse webResponse = HttpHelper.Post(url, "", null, headerDic, out string result);
if (webResponse != null && !string.IsNullOrEmpty(result))
{
JObject jsonObject = (JObject)JsonConvert.DeserializeObject(result);
string isSuccess = jsonObject["success"] + "";
if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase))
{
isDelete = true;
}
else
{
if (jsonObject.ContainsKey("msg"))
{
returnMsg = jsonObject["msg"] + "";
}
isDelete = false;
}
}
else
{
returnMsg = "删除请求失败";
isDelete = false;
}
}
else
{
returnMsg