using CRM.Core.Common.WebHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
namespace CRM.Core.Common.Ueditor
{
///
/// UploadHandler 的摘要说明
///
public class UploadHandler : Handler
{
public UploadConfig UploadConfig { get; private set; }
public UploadResult Result { get; private set; }
public UploadHandler(HttpContext context, UploadConfig config)
: base(context)
{
this.UploadConfig = config;
this.Result = new UploadResult() { State = UploadState.Unknown };
}
public override void Process()
{
byte[] uploadFileBytes = null;
string uploadFileName = null;
if (UploadConfig.Base64)
{
uploadFileName = UploadConfig.Base64Filename;
uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
}
else
{
var file = Request.Files[UploadConfig.UploadFieldName];
uploadFileName = file.FileName;
if (!CheckFileType(uploadFileName))
{
Result.State = UploadState.TypeNotAllow;
WriteResult();
return;
}
if (!CheckFileSize(file.ContentLength))
{
Result.State = UploadState.SizeLimitExceed;
WriteResult();
return;
}
int l = file.ContentLength;
Stream fs = file.InputStream;
try
{
using (var client = new HttpClient())
{
//获取token
var fileserver = WX.CRM.Common.Utility.GetSettingByKey("fileserver"); // "http://192.168.11.81:5300";
var gettokenUrl = $"{fileserver}/api/Token";
var data = Utility.GetData(gettokenUrl, "key=7AC51A5F0DE9A13D5FC9960AD45CC8D5");
var token = $"Bearer {data}";
HttpWebRequest request = WebRequest.Create($"{fileserver}/Streaming/UploadLargeFile") as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
request.Headers.Add("Authorization", token);
string fileName = uploadFileName;
//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
var res = JsonHelper.FromJson(content);
if (res.success == true)
{
Result.Url = res.url;
Result.State = UploadState.Success;
}
else
{
Result.State = UploadState.FileAccessError;
}
}
}
catch (Exception ex)
{
Result.State = UploadState.FileAccessError;
Result.ErrorMessage = ex.Message;
}
finally
{
WriteResult();
}
}
}
private void WriteResult()
{
this.WriteJson(new
{
state = GetStateMessage(Result.State),
url = Result.Url,
title = Result.OriginFileName,
original = Result.OriginFileName,
error = Result.ErrorMessage
});
}
private string GetStateMessage(UploadState state)
{
switch (state)
{
case UploadState.Success:
return "SUCCESS";
case UploadState.FileAccessError:
return "文件访问出错,请检查写入权限";
case UploadState.SizeLimitExceed:
return "文件大小超出服务器限制";
case UploadState.TypeNotAllow:
return "不允许的文件格式";
case UploadState.NetworkError:
return "网络错误";
}
return "未知错误";
}
private bool CheckFileType(string filename)
{
var fileExtension = Path.GetExtension(filename).ToLower();
return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
}
private bool CheckFileSize(int size)
{
return size < UploadConfig.SizeLimit;
}
}
public class UploadConfig
{
///
/// 文件命名规则
///
public string PathFormat { get; set; }
///
/// 上传表单域名称
///
public string UploadFieldName { get; set; }
///
/// 上传大小限制
///
public int SizeLimit { get; set; }
///
/// 上传允许的文件格式
///
public string[] AllowExtensions { get; set; }
///
/// 文件是否以 Base64 的形式上传
///
public bool Base64 { get; set; }
///
/// Base64 字符串所表示的文件名
///
public string Base64Filename { get; set; }
}
public class UploadResult
{
public UploadState State { get; set; }
public string Url { get; set; }
public string OriginFileName { get; set; }
public string ErrorMessage { get; set; }
}
public enum UploadState
{
Success = 0,
SizeLimitExceed = -1,
TypeNotAllow = -2,
FileAccessError = -3,
NetworkError = -4,
Unknown = 1,
}
public class UpLoadResult
{
public bool? isEnd { get; set; }
public bool? success { get; set; }
public string url { get; set; }
}
}