一、layui文件上传

<link rel="stylesheet" href="~/Content/layui/css/layui.css" media="all">
<script src="~/Content/layui/layui.js" charset="utf-8"></script>
<h2>Index</h2>
<br />

<div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>layUI上传</legend>
</fieldset>

<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="test8">选择文件</button>
<button type="button" class="layui-btn" id="test9">开始上传</button>
</div>

<script>
var _url = "http://localhost:53451/UploadingTools/upload_ajax.ashx?action=SingleFile";

layui.use(['upload','layer'], function () {
var $ = layui.jquery
, layer = layui.layer
, upload = layui.upload;

//选完文件后不自动上传
upload.render({
elem: '#test8'
, url: _url //改成您自己的上传接口
, auto: false
, bindAction: '#test9'
, choose: function (obj) {
//选择文件的回调
let the = this;
let name = $("input[name='file']")[0].files[0].name;
the.url = the.url + "&name=" + name;
console.log(the.url);

//预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
obj.preview(function (index, file, result) {
console.log(index); //得到文件索引
console.log(file); //得到文件对象
//console.log(result); //得到文件base64编码,比如图片
//layer.msg(file);
//file = JSON.stringify(file.File);
file = file.File.toString();

layer.alert(file);
});
}
, before: function (obj) {
}
, done: function (res, index, upload) {
layer.msg('上传成功');
console.log(res)
console.log(index)
console.log(res)
}
, error: function (index, upload) {
layer.msg('上传失败');
console.log(index)

}
});
});
</script>

</div>

二、手写-普通文件上传

<div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>手写-普通上传</legend>
</fieldset>
<form onsubmit="return false">
<input type="file" name="file2020" id="file2020" accept="image/*">
<br />

<input type="submit" value="提交-手写-普通上传" id="submit" class="layui-btn">
</form>
<script type="text/javascript">
var _url2 = "http://192.168.1.181:801/UploadingTools/upload_ajax.ashx?action=SingleFile";

$("#submit").on("click", function () {
check()
})

function check() {
console.log("自己写的");

//获取文件流
var fileInfo = $("#file2020");
var value = $("#file2020").val();
var ImageFileInfo = fileInfo[0].files[0];
var name = ImageFileInfo.name;
var size = ImageFileInfo.size;
var type = ImageFileInfo.type;

var form = $("form");
console.log(ImageFileInfo);

var news = $('#file2020')[0].files[0];
console.log(news);


//重构提交路径
_url2 += "&name=" + name
console.log(_url2);

//组织提交数据
var formData = new FormData();
formData.append("file",ImageFileInfo);
formData.append("filename", name);


$.ajax({
url: _url2,
dataType: 'json',
type: 'POST',
processData : false, // 使数据不做处理,告诉jQuery不要去处理发送的数据
contentType : false, // 不要设置Content-Type请求头,告诉jQuery不要去设置Content-Type请求头
data:formData,
success: function (data) {
console.log("成功后返回的数据");
console.log(data);
},
error: function (response) {
console.log("失败后返回的数据");
console.log(response);
}
});
}
</script>
</div>

三、上传并添加水印

<div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传并添加水印</legend>
</fieldset>
<form onsubmit="return false">
<input type="file" name="fileIsWater" id="fileIsWater" accept="image/*">
<br />

<input type="submit" value="提交-上传并添加水印" id="submitIsWater" class="layui-btn">
</form>
<script type="text/javascript">
var Url_IsWater = "http://localhost:53451/UploadingTools/upload_ajax.ashx?action=SingleFile";

$("#submitIsWater").on("click", function () {
IsWater()
})

function IsWater() {
console.log("上传并添加水印");

//获取文件流
var fileInfo = $("#fileIsWater");
var ImageFileInfo = fileInfo[0].files[0];
var name = ImageFileInfo.name;
console.log(name);
console.log(ImageFileInfo);

//重构提交路径
Url_IsWater += "&name=" + name+ "&IsWater=1"
console.log(Url_IsWater);

//组织提交数据
var formData = new FormData();
formData.append("file",ImageFileInfo);
formData.append("filename", name);


$.ajax({
url: Url_IsWater,
dataType: 'json',
type: 'POST',
processData : false, // 使数据不做处理,告诉jQuery不要去处理发送的数据
contentType : false, // 不要设置Content-Type请求头,告诉jQuery不要去设置Content-Type请求头
data:formData,
success: function (data) {
console.log("成功后返回的数据");
console.log(data);
},
error: function (response) {
console.log("失败后返回的数据");
console.log(response);
}
});
}
</script>
</div>

四、上传并生成缩略图

<div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传并生成缩略图</legend>
</fieldset>
<form onsubmit="return false">
<input type="file" name="fileIsThumbnail" id="fileIsThumbnail" accept="image/*">
<br />

<input type="submit" value="提交-上传并生成缩略图" id="submitIsThumbnail" class="layui-btn">
</form>
<script type="text/javascript">
var Url_IsWater = "http://localhost:53451/UploadingTools/upload_ajax.ashx?action=SingleFile";

$("#submitIsThumbnail").on("click", function () {
IsThumbnail()
})

function IsThumbnail() {
console.log("上传并生成缩略图");

//获取文件流
var fileInfo = $("#fileIsThumbnail");
var ImageFileInfo = fileInfo[0].files[0];
var name = ImageFileInfo.name;
console.log(name);
console.log(ImageFileInfo);

//重构提交路径
Url_IsWater += "&name=" + name+ "&IsThumbnail=1"
console.log(Url_IsWater);

//组织提交数据
var formData = new FormData();
formData.append("file",ImageFileInfo);
formData.append("filename", name);


$.ajax({
url: Url_IsWater,
dataType: 'json',
type: 'POST',
processData : false, // 使数据不做处理,告诉jQuery不要去处理发送的数据
contentType : false, // 不要设置Content-Type请求头,告诉jQuery不要去设置Content-Type请求头
data:formData,
success: function (data) {
console.log("成功后返回的数据");
console.log(data);
},
error: function (response) {
console.log("失败后返回的数据");
console.log(response);
}
});
}
</script>
</div>

五、上传并删除指定文件

<div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>上传并删除指定文件</legend>
</fieldset>
<form onsubmit="return false">
<input type="file" name="fileDelFilePath" id="fileDelFilePath" accept="image/*">
<br />

<input type="submit" value="提交-上传并删除指定文件" id="submitDelFilePath" class="layui-btn layui-btn-danger">
</form>
<script type="text/javascript">
var Url_DelFilePath = "http://localhost:53451/UploadingTools/upload_ajax.ashx?action=SingleFile";

$("#submitDelFilePath").on("click", function () {
DelFilePath()
})

function DelFilePath() {
console.log("上传并删除指定文件");

//获取文件流
var fileInfo = $("#fileDelFilePath");
var ImageFileInfo = fileInfo[0].files[0];
var name = ImageFileInfo.name;
console.log(name);
console.log(ImageFileInfo);

//重构提交路径
Url_DelFilePath += "&name=" + name+ "&DelFilePath=/upload/202010/31/thumb_202010311049181342.png"
console.log(Url_DelFilePath);

//组织提交数据
var formData = new FormData();
formData.append("file",ImageFileInfo);
formData.append("filename", name);


$.ajax({
url: Url_DelFilePath,
dataType: 'json',
type: 'POST',
processData : false, // 使数据不做处理,告诉jQuery不要去处理发送的数据
contentType : false, // 不要设置Content-Type请求头,告诉jQuery不要去设置Content-Type请求头
data:formData,
success: function (data) {
console.log("成功后返回的数据");
console.log(data);
},
error: function (response) {
console.log("失败后返回的数据");
console.log(response);
}
});
}
</script>
</div>

六、上传接口逻辑代码

这个上传接口是引用了一个 UploadingHelper类库,实现的,

c# net , layui文件上传,手写-普通文件上传,上传并添加水印,上传并生成缩略图,上传并删除指定文件,_数据

 c# net , layui文件上传,手写-普通文件上传,上传并添加水印,上传并生成缩略图,上传并删除指定文件,_上传_02

 

6.1upload_ajax.ashx接口逻辑代码 

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using UploadingHelper;
using LogHelper;

namespace WebApplication.UploadingTools
{
/// <summary>
/// upload_ajax 的摘要说明
/// </summary>
public class upload_ajax : IHttpHandler, IRequiresSessionState
{
private UploadingHelper.Model.sysconfig sysConfig = new UploadingHelper.BLL.sysconfig().loadConfig();

/// <summary>
/// 返回status:0 失败
/// 返回status:1 成功
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{

#region******验证域名,并记录访问日志******
StringBuilder strB = new StringBuilder();

if (context.Request.UrlReferrer != null)
{
strB.Append(context.Request.UrlReferrer.ToString());
strB.Append("\n检查请求域名是否合法");

//检查请求域名是否合法
if (!CheckDomainName.Check(context, sysConfig))
{
strB.Append("\n检查结果:违法");
//返回信息
context.Response.Write("{\"status\": 0, \"msg\": \"违法\"}");
context.Response.End();
return;
}
strB.Append("\n检查结果:允许");
}
else {
strB.Append("\n Request.UrlReferrer为空,可能是手机访问");
strB.Append("\n 开始记录手机信息");
strB.Append($"\n UserAgent:{context.Request.UserAgent}");
strB.Append($"\n UserHostAddress:{context.Request.UserHostAddress}");
strB.Append($"\n UserHostName:{context.Request.UserHostName}");
}
Log.Info(strB.ToString());
#endregion


//取得处事类型
string action = UploadingHelperRequest.GetQueryString("action");

switch (action)
{
case "config": //编辑器配置
EditorConfig(context);
break;
case "uploadimage": //编辑器上传图片
EditorUploadImage(context);
break;
case "uploadvideo": //编辑器上传视频
EditorUploadVideo(context);
break;
case "uploadfile": //编辑器上传附件
EditorUploadFile(context);
break;
case "uploadscrawl": //编辑器上传涂鸦
EditorUploadScrawl(context);
break;
case "listimage": //编辑器浏览图片
EditorListImage(context);
break;
case "listfile": //编辑器浏览文件
EditorListFile(context);
break;
case "catchimage": //编辑器远程抓取图片
EditorCatchImage(context);
break;
default: //普通上传
UpLoadFile(context);
break;
}


}

#region 上传文件处理===================================
private void UpLoadFile(HttpContext context)
{

//检查是否允许匿名上传
/*if (sysConfig.fileanonymous == 0 && !new ManagePage().IsAdminLogin() && !new BasePage().IsUserLogin())
{
context.Response.Write("{\"status\": 0, \"msg\": \"禁止匿名非法上传!\"}");
return;
}*/

string _delfile = UploadingHelperRequest.GetString("DelFilePath"); //要删除的文件
//string fileName = UploadingHelperRequest.GetString("name"); //从请求路径中获取文件名
string fileName = context.Request.Files["file"].FileName; //从提交文件流中获取文件名

//获取文件流 方式有2种,根据不通的传参有可能需要修改
//1.context.Request.Files["file"].InputStream
//2.context.Request.InputStream
Stream InputStream = context.Request.Files["file"].InputStream;
byte[] byteData = UploadingHelper.Common.FileHelper.ConvertStreamToByteBuffer(InputStream); //获取文件流

bool _iswater = false; //默认不打水印
bool _isthumbnail = false; //默认不生成缩略图

if (UploadingHelperRequest.GetQueryString("IsWater") == "1")
{
_iswater = true;
}
if (UploadingHelperRequest.GetQueryString("IsThumbnail") == "1")
{
_isthumbnail = true;
}
if (byteData.Length == 0)
{
context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传文件!\"}");
return;
}
UpLoad upLoad = new UpLoad();
string msg = upLoad.FileSaveAs(byteData, fileName, _isthumbnail, _iswater);

//删除已存在的旧文件
if (!string.IsNullOrEmpty(_delfile))
{
upLoad.DeleteFile(_delfile);
}
//返回成功信息
context.Response.Write(msg);
context.Response.End();
}
#endregion

#region 辅助工具方法===================================
/// <summary>
/// 统一保存文件
/// </summary>
private void FileSave(HttpContext context, HttpPostedFile upFiles, bool isWater)
{
if (upFiles == null)
{
showError(context, "请选择要上传文件!");
return;
}
//检查是否允许匿名上传
/*if (sysConfig.fileanonymous == 0 && !new ManagePage().IsAdminLogin() && !new BasePage().IsUserLogin())
{
showError(context, "禁止匿名非法上传!");
return;
}*/
//获取文件信息
string fileName = upFiles.FileName;
byte[] byteData = UploadingHelper.Common.FileHelper.ConvertStreamToByteBuffer(upFiles.InputStream); //获取文件流
//开始上传
string remsg = new UpLoad().FileSaveAs(byteData, fileName, false, isWater);
Dictionary<string, object> dic = UploadingHelper.Common.JsonHelper.DataRowFromJSON(remsg);
string status = dic["status"].ToString();
string msg = dic["msg"].ToString();
if (status == "0")
{
showError(context, msg);
return;
}
string filePath = dic["path"].ToString(); //取得上传后的路径
showSuccess(context, fileName, filePath); //输出成功提示
}

/// <summary>
/// 显示错误提示
/// </summary>
private void showError(HttpContext context, string message)
{
Hashtable hash = new Hashtable();
hash["state"] = message;
hash["error"] = message;
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(UploadingHelper.Common.JsonHelper.ObjectToJSON(hash));
context.Response.End();
}

/// <summary>
/// 显示成功提示
/// </summary>
private void showSuccess(HttpContext context, string fileName, string filePath)
{
Hashtable hash = new Hashtable();
hash["state"] = "SUCCESS";
hash["url"] = filePath;
hash["title"] = fileName;
hash["original"] = fileName;
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(UploadingHelper.Common.JsonHelper.ObjectToJSON(hash));
context.Response.End();
}

/// <summary>
/// 重新组合扩展名
/// </summary>
private string GetExtension(string extStr)
{
if (string.IsNullOrEmpty(extStr))
{
return "[]";
}
string[] strArr = extStr.Split(',');
StringBuilder sb = new StringBuilder();
foreach (string str in strArr)
{
sb.Append("\"." + str + "\",");
}
return "[" + sb.ToString().TrimEnd(',') + "]";
}

/// <summary>
/// 浏览目录文件
/// </summary>
private void ListFileManager(HttpContext context, string filePath, string fileTypes)
{
int Start = UploadingHelperRequest.GetInt("start", 0); //开始索引
int Size = UploadingHelperRequest.GetInt("size", 20); //每页大小
int Total = 0; //文件总数
string State = "SUCCESS"; //状态,默认成功
String[] FileList = null;

var buildingList = new List<String>();
try
{
var localPath = UploadingHelper.Common.Utils.GetMapPath(filePath);
buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
.Where(x => fileTypes.Contains(Path.GetExtension(x).ToLower()))
.Select(x => filePath + x.Substring(localPath.Length).Replace("\\", "/")));
Total = buildingList.Count;
FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
}
catch (UnauthorizedAccessException)
{
State = "文件系统权限不足";
}
catch (DirectoryNotFoundException)
{
State = "路径不存在";
}
catch (IOException)
{
State = "文件系统读取错误";
}
finally
{
Hashtable hash = new Hashtable();
hash["state"] = State;
hash["list"] = FileList == null ? null : FileList.Select(x => new { url = x });
hash["start"] = Start;
hash["total"] = Total;
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(UploadingHelper.Common.JsonHelper.ObjectToJSON(hash));
context.Response.End();
}
}

#endregion

#region 编辑器请求处理=================================
/// <summary>
/// 初始化参数
/// </summary>
private void EditorConfig(HttpContext context)
{
UploadingHelper.Model.sysconfig sysConfig = new UploadingHelper.BLL.sysconfig().loadConfig();
StringBuilder jsonStr = new StringBuilder();
jsonStr.Append("{");
//上传图片配置项
jsonStr.Append("\"imageActionName\": \"uploadimage\","); //执行上传图片的action名称
jsonStr.Append("\"imageFieldName\": \"upfile\","); //提交的图片表单名称
jsonStr.Append("\"imageMaxSize\": " + (sysConfig.imgsize * 1024) + ","); //上传大小限制,单位B
jsonStr.Append("\"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],"); //上传图片格式显示
jsonStr.Append("\"imageCompressEnable\": false,"); //是否压缩图片,默认是true
jsonStr.Append("\"imageCompressBorder\": 1600,"); //图片压缩最长边限制
jsonStr.Append("\"imageInsertAlign\": \"none\","); //插入的图片浮动方式
jsonStr.Append("\"imageUrlPrefix\": \"\","); //图片访问路径前缀
jsonStr.Append("\"imagePathFormat\": \"\","); //上传保存路径
//涂鸦图片上传配置项
jsonStr.Append("\"scrawlActionName\": \"uploadscrawl\","); //执行上传涂鸦的action名称
jsonStr.Append("\"scrawlFieldName\": \"upfile\","); //提交的图片表单名称
jsonStr.Append("\"scrawlPathFormat\": \"\","); //上传保存路径
jsonStr.Append("\"scrawlMaxSize\": " + (sysConfig.imgsize * 1024) + ","); //上传大小限制,单位B
jsonStr.Append("\"scrawlUrlPrefix\": \"\","); //图片访问路径前缀
jsonStr.Append("\"scrawlInsertAlign\": \"none\",");
//截图工具上传
jsonStr.Append("\"snapscreenActionName\": \"uploadimage\","); //执行上传截图的action名称
jsonStr.Append("\"snapscreenPathFormat\": \"\","); //上传保存路径
jsonStr.Append("\"snapscreenUrlPrefix\": \"\","); //图片访问路径前缀
jsonStr.Append("\"snapscreenInsertAlign\": \"none\","); //插入的图片浮动方式
//抓取远程图片配置
jsonStr.Append("\"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],");
jsonStr.Append("\"catcherActionName\": \"catchimage\","); //执行抓取远程图片的action名称
jsonStr.Append("\"catcherFieldName\": \"source\","); //提交的图片列表表单名称
jsonStr.Append("\"catcherPathFormat\": \"\","); //上传保存路径
jsonStr.Append("\"catcherUrlPrefix\": \"\","); //图片访问路径前缀
jsonStr.Append("\"catcherMaxSize\": " + (sysConfig.imgsize * 1024) + ","); //上传大小限制,单位B
jsonStr.Append("\"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],"); //抓取图片格式显示
//上传视频配置
jsonStr.Append("\"videoActionName\": \"uploadvideo\","); //上传视频的action名称
jsonStr.Append("\"videoFieldName\": \"upfile\","); //提交的视频表单名称
jsonStr.Append("\"videoPathFormat\": \"\","); //上传保存路径
jsonStr.Append("\"videoUrlPrefix\": \"\","); //视频访问路径前缀
jsonStr.Append("\"videoMaxSize\": " + (sysConfig.videosize * 1024) + ","); //上传大小限制,单位B
jsonStr.Append("\"videoAllowFiles\": " + GetExtension(sysConfig.videoextension) + ",");
//上传附件配置
jsonStr.Append("\"fileActionName\": \"uploadfile\","); //上传视频的action名称
jsonStr.Append("\"fileFieldName\": \"upfile\","); //提交的文件表单名称
jsonStr.Append("\"filePathFormat\": \"\","); //上传保存路径
jsonStr.Append("\"fileUrlPrefix\": \"\","); //文件访问路径前缀
jsonStr.Append("\"fileMaxSize\": " + (sysConfig.attachsize * 1024) + ","); //上传大小限制,单位B
jsonStr.Append("\"fileAllowFiles\": " + GetExtension(sysConfig.fileextension) + ","); //上传文件格式
//列出指定目录下的图片
jsonStr.Append("\"imageManagerActionName\": \"listimage\","); //执行图片管理的action名称
jsonStr.Append("\"imageManagerListPath\": \"\","); //指定要列出图片的目录
jsonStr.Append("\"imageManagerListSize\": 20,"); //每次列出文件数量
jsonStr.Append("\"imageManagerUrlPrefix\": \"\","); //图片访问路径前缀
jsonStr.Append("\"imageManagerInsertAlign\": \"none\","); //插入的图片浮动方式
jsonStr.Append("\"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],"); //列出的文件类型
//列出指定目录下的文件
jsonStr.Append("\"fileManagerActionName\": \"listfile\","); //执行文件管理的action名称
jsonStr.Append("\"fileManagerListPath\": \"\","); //指定要列出文件的目录
jsonStr.Append("\"fileManagerUrlPrefix\": \"\","); //文件访问路径前缀
jsonStr.Append("\"fileManagerListSize\": 20,"); //每次列出文件数量
jsonStr.Append("\"fileManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",");
jsonStr.Append("\".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",");
jsonStr.Append("\".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",");
jsonStr.Append("\".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",");
jsonStr.Append("\".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"]");
jsonStr.Append("}");

context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(jsonStr.ToString());
context.Response.End();
}

/// <summary>
/// 上传图片
/// </summary>
private void EditorUploadImage(HttpContext context)
{
bool _iswater = true; //默认打水印
/*if (DTRequest.GetQueryString("IsWater") == "1")
{
_iswater = true;
}*/
HttpPostedFile upFile = context.Request.Files["upfile"];
FileSave(context, upFile, _iswater);
}

/// <summary>
/// 上传视频
/// </summary>
private void EditorUploadVideo(HttpContext context)
{
HttpPostedFile upFile = context.Request.Files["upfile"];
FileSave(context, upFile, false);
}

/// <summary>
/// 上传附件
/// </summary>
private void EditorUploadFile(HttpContext context)
{
HttpPostedFile upFile = context.Request.Files["upfile"];
FileSave(context, upFile, false);
}

/// <summary>
/// 上传涂鸦
/// </summary>
private void EditorUploadScrawl(HttpContext context)
{
byte[] byteData = Convert.FromBase64String(context.Request["upfile"]);
string fileName = "scrawl.png";
//开始上传
string remsg = new UpLoad().FileSaveAs(byteData, fileName, false, false);
Dictionary<string, object> dic = UploadingHelper.Common.JsonHelper.DataRowFromJSON(remsg);
string status = dic["status"].ToString();
string msg = dic["msg"].ToString();
if (status == "0")
{
showError(context, msg);
return;
}
string filePath = dic["path"].ToString(); //取得上传后的路径
showSuccess(context, fileName, filePath); //输出成功提示
}

/// <summary>
/// 浏览图片
/// </summary>
private void EditorListImage(HttpContext context)
{
UploadingHelper.Model.sysconfig sysConfig = new UploadingHelper.BLL.sysconfig().loadConfig();
string filePath = sysConfig.webpath + sysConfig.filepath + "/"; //站点目录+上传目录
string fileTypes = ".gif,.jpg,.jpeg,.png,.bmp"; //允许浏览的文件扩展名
ListFileManager(context, filePath, fileTypes);
}

/// <summary>
/// 浏览文件
/// </summary>
private void EditorListFile(HttpContext context)
{
UploadingHelper.Model.sysconfig sysConfig = new UploadingHelper.BLL.sysconfig().loadConfig();
string filePath = sysConfig.webpath + sysConfig.filepath + "/"; //站点目录+上传目录
string fileTypes = ".png,.jpg,.jpeg,.gif,.bmp,.flv,.swf,.mkv,.avi,.rm,.rmvb,.mpeg,.mpg,.ogg,.ogv,.mov,.wmv,"
+ ".mp4,.webm,.mp3,.wav,.mid,.rar,.zip,.tar,.gz,.7z,.bz2,.cab,.iso,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.md,.xml"; //允许浏览的文件扩展名
ListFileManager(context, filePath, fileTypes);
}

/// <summary>
/// 抓取远程图片
/// </summary>
private void EditorCatchImage(HttpContext context)
{
UploadingHelper.Model.sysconfig sysConfig = new UploadingHelper.BLL.sysconfig().loadConfig();
if (sysConfig.fileremote == 0)
{
Hashtable hash = new Hashtable();
hash["state"] = "未开启远程图片本地化";
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(UploadingHelper.Common.JsonHelper.ObjectToJSON(hash));
context.Response.End();
}
string[] sourcesUriArr = context.Request.Form.GetValues("source[]");
if (sourcesUriArr == null || sourcesUriArr.Length == 0)
{
Hashtable hash = new Hashtable();
hash["state"] = "参数错误:没有指定抓取源";
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(UploadingHelper.Common.JsonHelper.ObjectToJSON(hash));
context.Response.End();
}
UpLoad upLoad = new UpLoad(); //初始化上传类
List<Hashtable> fileList = new List<Hashtable>(); //存储上传成功的文件列表
foreach (string sourcesUri in sourcesUriArr)
{
string remsg = upLoad.RemoteSaveAs(sourcesUri);
Dictionary<string, object> dic = UploadingHelper.Common.JsonHelper.DataRowFromJSON(remsg);
//如果抓取成功则加入文件列表
if (dic["status"].ToString() == "1")
{
Hashtable hash = new Hashtable();
hash["state"] = "SUCCESS";
hash["source"] = sourcesUri;
hash["url"] = dic["path"].ToString();
fileList.Add(hash);
}
}
Hashtable result = new Hashtable();
result["state"] = "SUCCESS";
result["list"] = fileList;
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.Write(UploadingHelper.Common.JsonHelper.ObjectToJSON(result));
context.Response.End();
}
#endregion
public bool IsReusable
{
get
{
return false;
}
}


}
}

6.2 上传配置文件Uploading.config

<?xml version="1.0"?>
<sysconfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--名字-->
<name>UploadingHelperXML</name>
<!--作者-->
<author>CPLVFX</author>
<!--网站安装目录-->
<webpath>/</webpath>
<!--编辑器远程图片上传0:关闭下载1:自动下载 -->
<fileremote>0</fileremote>
<!--上传文件保存路径-->
<filepath>upload</filepath>
<!--文件保存 2:按年月/日/存入不同目录-->
<filesave>2</filesave>
<!--文件匿名 允许匿名上传(0否1是)-->
<fileanonymous>1</fileanonymous>
<!--文件上传类型:*以英文的逗号分隔开,如:“zip,rar”-->
<fileextension>gif,jpg,jpeg,png,bmp,rar,zip,doc,xls,txt</fileextension>
<!--视频上传类型:*以英文的逗号分隔开,如:“mp4,flv”-->
<videoextension>flv,mp3,mp4,avi</videoextension>
<!--附件上传大小:单位KB *超过设定的文件大小不予上传,0不限制-->
<attachsize>51200</attachsize>
<!--视频上传大小:单位KB *超过设定的文件大小不予上传,0不限制-->
<videosize>102400</videosize>
<!--图片上传大小:单位KB *超过设定的图片大小不予上传,0不限制-->
<imgsize>10240</imgsize>
<!--图片最大尺寸:单位px *左边高度,右边宽度,超出自动裁剪,0为不受限制-->
<imgmaxheight>1600</imgmaxheight>
<imgmaxwidth>1600</imgmaxwidth>
<!--缩略图生成尺寸:px *左边高度,右边宽度,0为不生成缩略图-->
<thumbnailheight>300</thumbnailheight>
<thumbnailwidth>300</thumbnailwidth>
<!--
缩略图生成方式:
裁剪:Cut
补白:HW
-->
<thumbnailmode>Cut</thumbnailmode>
<!--
图片水印类型:
0:关闭水印
1:文字水印
2:图片水印
-->
<watermarktype>2</watermarktype>
<!--
图片水印位置:
1:左上,
2:中上,
3:右上,
4:左中,
5:居中,
6:右中,
7:左下,
8:中下,
9:右下
-->
<watermarkposition>9</watermarkposition>
<!--图片生成质量:*只适用于加水印的jpeg格式图片.取值范围 0-100, 0质量最低, 100质量最高, 默认80-->
<watermarkimgquality>80</watermarkimgquality>
<!--图片水印文件:*需存放在站点目录下,如图片不存在将使用文字水印-->
<watermarkpic>watermark.png</watermarkpic>
<!--水印透明度:*取值范围1到10 (10为不透明)-->
<watermarktransparency>5</watermarktransparency>
<!--水印文字:*文字水印的内容-->
<watermarktext>CPLVFX</watermarktext>
<!--文字字体-->
<watermarkfont>Tahoma</watermarkfont>
<!--字号-->
<watermarkfontsize>12</watermarkfontsize>

<!--上传请求域名过滤;多个域名用英文,逗号隔开(*项目上线后一定要把测试域名删掉)-->
<CheckDomainName>http://192.168.1.181/,http://localhost/,http://127.0.0.1/</CheckDomainName>
</sysconfig>