框架\wwwroot\lib\imageupload\1.0\js路径下imgup.js文件,参照旧版本代码和修改代码修改
-
- (function ($) {
- "use strict";
-
- var deleteParent;
- var deleteDisplay = 'none';
- var defaults = {
- fileType: ["jpg", "png", "bmp", "jpeg", "gif"], // 上传文件的类型
- fileSize: 1024 * 1024 * 200 // 上传文件的大小 10M
- };
-
- $.fn.imageUpload = function (option, param) {
- if (typeof option == 'string') {
- return $.fn.imageUpload.methods[option](this, param);
- }
- var _option = $.extend({}, $.fn.imageUpload.defaults, option || {});
- var target = $(this);
- var id = target.attr("id");
- var inputFileId = id + "_file";
- var html = '';
- html += '
' ; - html += ' ';
- html += '
' ; - if (_option.canAdd == 1) {
- html += ' context + 'lib/imageupload/1.0/img/add.png" class="add-img">';
- deleteDisplay = 'block';
- }
- /**
- * 旧版本代码
- */
- //html += ' // + '" class="file-image" callback="' + _option.uploadImage + '" context="'
- // + _option.context + '" limit="' + _option.limit
- // + '" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" />';
- /**
- * 20231024修改
- * 为input元素增加multiple属性
- */
- html += ' '" id="' + inputFileId
- + '" class="file-image" callback="' + _option.uploadImage + '" context="'
- + _option.context + '" multiple limit="' + _option.limit
- + '" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" />';
- html += ' ';
- html += ' ';
- html += '';
- html += ';
- html += ' ';
- html += ' 您确定要删除图片吗?';
- html += ' 确定取消';
- html += ' ';
- html += '';
- target.append(html);
-
- target.find(".wsdel-ok").click(function () {
- $(".works-mask").hide();
- var numUp = deleteParent.siblings().length;
- if (numUp < 6) {
- deleteParent.parent().find(".z_file").show();
- }
- deleteParent.remove();
- });
-
- target.find(".wsdel-no").click(function () {
- $(".works-mask").hide();
- });
-
- $("#" + inputFileId).change(function () {
- prepareUploadImage(inputFileId);
- });
- };
-
- $.fn.imageUpload.defaults = {
- uploadImage: '', // 上传图片回调
- limit: 10, // 上传限制
- context: '', // 当前页面根目录
- canPreview: 1, // 是否可以预览(0不可以,1可以)
- canAdd: 1 // 是否可以添加(0不可以,1可以)
- };
-
- $.fn.imageUpload.methods = {
- getImageUrl: function (target) {
- var imageUrl = '';
- var list = $(target).find('.up-section').find('.up-img');
- for (var i = 0; i < list.length; i++) {
- if (i == 0) {
- imageUrl += $(list[i]).attr("src");
- } else {
- imageUrl += ';';
- imageUrl += $(list[i]).attr("src");
- }
- }
- return imageUrl;
- },
- setImageUrl: function (target, imageUrl) {
- if (imageUrl) {
- var id = $(target).attr("id");
- var inputFileId = id + "_file";
- var context = $("#" + inputFileId).attr("context");
-
- var urlArr = imageUrl.split(';');
- for (var i = 0; i < urlArr.length; i++) {
- if (urlArr[i] != "") {
- var deleteId = ys.getGuid();
- var imageName = urlArr[i].substring(urlArr[i].lastIndexOf('/') + 1);
- var html = '';
- html += '
' ; - html += ' ';
-
- html += ' '" class="close-upimg" style="display:' + deleteDisplay + '" src="' + context + 'lib/imageupload/1.0/img/delete.png" />';
- if (urlArr[i].indexOf('http') > -1) {
- html += ' '" />';
- }
- else {
- html += ' trimStart(urlArr[i], '/') + '" />';
- }
- html += '
"'
+ imageName + '"'; - html += '';
- $(html).insertBefore($(target).find(".z_file"));
- $("#" + deleteId).on("click", function () {
- $("#" + inputFileId).imageUpload("deleteImage", deleteId)
- });
- }
- }
- $(".up-span").Huipreview();
- $("#" + inputFileId).imageUpload("checkImageLimit")
- }
- },
- deleteImage: function (target, deleteId) {
- var _target = $(target);
- var inputFileId = _target.attr("id");
- if (!!event) {
- event.preventDefault();
- event.stopPropagation();
- }
- $(".works-mask").show();
- deleteParent = $("#" + deleteId).parent();
- $("#" + inputFileId).imageUpload("checkImageLimit");
- },
- checkImageLimit: function (target) {
- var _target = $(target);
- var num = _target.parents(".z_photo").find(".up-section").length;
- var limit = _target.attr("limit");
- if (num >= limit) {
- _target.parent().hide();
- } else {
- _target.parent().show();
- }
- }
- };
-
- function prepareUploadImage(inputFileId) {
- var target = $("#" + inputFileId);
- var callback = target.attr("callback");
- var limit = target.attr("limit");
- if (!callback || callback == '') {
- alert("请提供上传方法");
- return;
- }
- var inputFile = document.getElementById(inputFileId);
- var imgContainer = target.parents(".z_photo"); //存放图片的父亲元素
- var fileList = inputFile.files; //获取的图片文件
- //遍历得到的图片文件
- var num = imgContainer.find(".up-section").length;
- var totalNum = num + fileList.length; //总的数量
- if (fileList.length > limit || totalNum > limit) {
- alert("上传图片数目不可以超过" + limit + "个,请重新选择"); //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
- }
- else if (num < limit) {
-
- validateUpload(fileList);
-
- var uploadSuccess = function (imgPath) {
-
- /**
- * 旧版本代码
- */
- //var section = $("
"); - //imgContainer.prepend(section);
- //var span = $("");
- //span.appendTo(section);
-
- //var context = $("#" + inputFileId).attr("context");
- //var deleteId = ys.getGuid();
- //var deleteImg = $(" style='display:" + deleteDisplay + "'").on("click", function () {
- // $("#" + inputFileId).imageUpload("deleteImage", deleteId)
- //});
- //deleteImg.attr("src", context + "lib/imageupload/1.0/img/delete.png").appendTo(section);
-
- //var realImg = $("");
- //realImg.attr("src", imgPath);
- //realImg.appendTo(section);
- //var p = $("
");
- //p.html(imgPath.substring(imgPath.lastIndexOf('/') + 1)).appendTo(section);
-
- /**
- * 20231024修改
- * 增加方法多文件上传功能
- */
- if (typeof (imgPath) == 'string') {
- var section = $("
" ); - imgContainer.prepend(section);
- var span = $("");
- span.appendTo(section);
-
- var context = $("#" + inputFileId).attr("context");
- var deleteId = ys.getGuid();
- var deleteImg = $(" style='display:" + deleteDisplay + "'").on("click", function () {
- $("#" + inputFileId).imageUpload("deleteImage", deleteId)
- });
- deleteImg.attr("src", context + "lib/imageupload/1.0/img/delete.png").appendTo(section);
-
- var realImg = $("");
- realImg.attr("src", imgPath);
- realImg.appendTo(section);
- var p = $("
"
); - p.html(imgPath.substring(imgPath.lastIndexOf('/') + 1)).appendTo(section);
- }
- else {
- imgPath.forEach(function (item) {
- var section = $("
" ); - imgContainer.prepend(section);
- var span = $("");
- span.appendTo(section);
-
- var context = $("#" + inputFileId).attr("context");
- var deleteId = ys.getGuid();
- var deleteImg = $(" style='display:" + deleteDisplay + "'").on("click", function () {
- $("#" + inputFileId).imageUpload("deleteImage", deleteId)
- });
- deleteImg.attr("src", context + "lib/imageupload/1.0/img/delete.png").appendTo(section);
-
- var realImg = $("");
- realImg.attr("src", item);
- realImg.appendTo(section);
- var p = $("
"
); - p.html(item.substring(item.lastIndexOf('/') + 1)).appendTo(section);
- })
- }
-
- setTimeout(function () {
- $(".up-section").removeClass("loading");
- $(".up-img").removeClass("up-opcity");
- }, 450);
-
- $("#" + inputFileId).imageUpload("checkImageLimit");
- };
-
- /**
- * 旧版本代码
- */
- //var currentFile = fileList[fileList.length - 1];//只返回最后一个文件内容
- //doCallback(eval(callback), [currentFile, uploadSuccess]);
-
- /**
- * 20231024修改
- * 将所有的上传内容返回自定义方法
- */
- doCallback(eval(callback), [fileList, uploadSuccess]);
- }
- }
-
- function validateUpload(files) {
- var arrFiles = [];//替换的文件数组
- for (var i = 0, file; file = files[i]; i++) {
- //获取文件上传的后缀名
- var newStr = file.name.split("").reverse().join("");
- if (newStr.split(".")[0] != null) {
- var type = newStr.split(".")[0].split("").reverse().join("");
- console.log(type + "===type===");
- if (jQuery.inArray(type, defaults.fileType) > -1) {
- // 类型符合,可以上传
- if (file.size >= defaults.fileSize) {
- alert(file.size);
- alert('您这个"' + file.name + '"文件大小过大');
- } else {
- // 在这里需要判断当前所有文件中
- arrFiles.push(file);
- }
- } else {
- alert('您这个"' + file.name + '"上传类型不符合');
- }
- } else {
- alert('您这个"' + file.name + '"没有类型, 无法识别');
- }
- }
- return arrFiles;
- }
-
- // 动态调用方法,并传递参数
- function doCallback(fn, args) {
- fn.apply(this, args);
- }
- })(jQuery);
-
页面代码,替换原有页面初始化和自定义上传触发方法
- //初始化组件方法
- $("#thumbImage").imageUpload({ uploadImage: 'uploadThumbImage', limit: 10, context: ctx });//limit参数,设置单次上传和总上传数量
-
- function uploadThumbImage(file, callback) {//自定义的上传触发方法
- var formdata = new FormData();
- //formdata.append("fileList", file);//file为单文件数据(File类型)
- console.log('uploadThumbImage', file)
- for (var i = 0; i < file.length; i++) {//file为多文件数据(FileList类型)
- formdata.append("fileList", file[i]);//手动给formdata中添加文件流内容
- }
- ys.ajaxUploadFile({
- //url: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.News.ParseToInt()',
- url: '@Url.Content("~/File/uploadImagesProc")' + "?fileModule=@UploadFileType.News.ParseToInt()",
- data: formdata,
- success: function (obj) {
- if (obj.Tag == 1) {
- if (callback) {
- //callback('@GlobalContext.SystemConfig.ApiSite' + obj.Data);
- callback(obj.Data);
- }
- }
- else {
- ys.msgError(obj.Message);
- }
- }
- })
- }
后台代码,可直接复制,UploadFileProc方法需在FileHelper类中创建
- ///
- /// 单/多文件上传
- ///
- ///
- ///
- [HttpPost]
- public async Task
object>> uploadImagesProc(int fileModule, IFormFileCollection fileList) - {
- TData<object> obj = new TData<object>();
- obj = await FileHelper.UploadFileProc(fileModule, fileList);
- return obj;
-
- }
- #region 上传多个文件
- ///
- /// 上传多个文件
- ///
- ///
- /// 文件流集合
- ///
- public async static Task
object>> UploadFileProc(int fileModule, IFormFileCollection files) - {
- string dirModule = string.Empty;
- TData<object> obj = new TData<object>();
- if (files == null || files.Count == 0)
- {
- obj.Message = "请先选择文件!";
- return obj;
- }
- //IFormFile file = files[0];
- List<object> resultObj = new List<object>();
- foreach (IFormFile file in files)
- {
- TData objCheck = null;
- objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png");
- if (objCheck.Tag != 1)
- {
- obj.Tag = 0;
- obj.Message = objCheck.Message;
- return obj;
- }
- switch (fileModule)
- {
- case (int)UploadFileType.Portrait:
- objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png");
- if (objCheck.Tag != 1)
- {
- obj.Message = objCheck.Message;
- return obj;
- }
- dirModule = UploadFileType.Portrait.ToString();
- break;
-
- case (int)UploadFileType.News:
- if (file.Length > 5 * 1024 * 1024) // 5MB
- {
- obj.Message = "文件最大限制为 5MB";
- return obj;
- }
- objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png");
- if (objCheck.Tag != 1)
- {
- obj.Message = objCheck.Message;
- return obj;
- }
- dirModule = UploadFileType.News.ToString();
- break;
-
- case (int)UploadFileType.Import:
- objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".xls|.xlsx");
- if (objCheck.Tag != 1)
- {
- obj.Message = objCheck.Message;
- return obj;
- }
- dirModule = UploadFileType.Import.ToString();
- break;
-
- default:
- obj.Message = "请指定上传到的模块";
- return obj;
- }
- string fileExtension = TextHelper.GetCustomValue(Path.GetExtension(file.FileName), ".png");
-
- string newFileName = SecurityHelper.GetGuid() + fileExtension;
- string dir = "Resource" + Path.DirectorySeparatorChar + dirModule + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd").Replace('-', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
-
- string absoluteDir = Path.Combine(GlobalContext.HostingEnvironment.ContentRootPath, dir);
- string absoluteFileName = string.Empty;
- if (!Directory.Exists(absoluteDir))
- {
- Directory.CreateDirectory(absoluteDir);
- }
- absoluteFileName = absoluteDir + newFileName;
- try
- {
- using (FileStream fs = System.IO.File.Create(absoluteFileName))
- {
- await file.CopyToAsync(fs);
- fs.Flush();
- }
- resultObj.Add(Path.AltDirectorySeparatorChar + ConvertDirectoryToHttp(dir) + newFileName);
- //obj.Data = ;
- //obj.Message = Path.GetFileNameWithoutExtension(TextHelper.GetCustomValue(file.FileName, newFileName));
- //obj.Description = (file.Length / 1024).ToString(); // KB
- //obj.Tag = 1;
- }
- catch (Exception ex)
- {
- obj.Tag = 0;
- obj.Message = ex.Message;
-
- }
-
- }
- if (resultObj.Count > 0)
- {
- obj.Tag = 1;
- obj.Message = "上传成功";
- obj.Data = resultObj;
- }
- return obj;
- }
- #endregion
-
-
- public static string ConvertDirectoryToHttp(string directory)
- {
- directory = directory.ParseToString();
- directory = directory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- return directory;
- }
-
-
- public static TData CheckFileExtension(string fileExtension, string allowExtension)
- {
- TData obj = new TData();
- string[] allowArr = TextHelper.SplitToArray<string>(allowExtension.ToLower(), '|');
- if (allowArr.Where(p => p.Trim() == fileExtension.ParseToString().ToLower()).Any())
- {
- obj.Tag = 1;
- }
- else
- {
- obj.Message = "只有文件扩展名是 " + allowExtension + " 的文件才能上传";
- }
- return obj;
- }
-
-
- public class TextHelper
- {
- ///
- /// 获取默认值
- ///
- ///
- ///
- ///
- public static string GetCustomValue(string value, string defaultValue)
- {
- if (string.IsNullOrEmpty(value))
- {
- return defaultValue;
- }
- else
- {
- return value;
- }
- }
-
- ///
- /// 截取指定长度的字符串
- ///
- ///
- ///
- ///
- public static string GetSubString(string value, int length, bool ellipsis = false)
- {
- if (string.IsNullOrEmpty(value))
- {
- return value;
- }
- if (value.Length > length)
- {
- value = value.Substring(0, length);
- if (ellipsis)
- {
- value += "...";
- }
- }
- return value;
- }
-
- ///
- /// 字符串转指定类型数组
- ///
- ///
- ///
- ///
- public static T[] SplitToArray<T>(string value, char split)
- {
- T[] arr = value.Split(new string[] { split.ToString() }, StringSplitOptions.RemoveEmptyEntries).CastSuper
().ToArray(); - return arr;
- }
- }