• 【.net core】yisha框架imageupload组件多图上传修改


     框架\wwwroot\lib\imageupload\1.0\js路径下imgup.js文件,参照旧版本代码和修改代码修改

    1. (function ($) {
    2. "use strict";
    3. var deleteParent;
    4. var deleteDisplay = 'none';
    5. var defaults = {
    6. fileType: ["jpg", "png", "bmp", "jpeg", "gif"], // 上传文件的类型
    7. fileSize: 1024 * 1024 * 200 // 上传文件的大小 10M
    8. };
    9. $.fn.imageUpload = function (option, param) {
    10. if (typeof option == 'string') {
    11. return $.fn.imageUpload.methods[option](this, param);
    12. }
    13. var _option = $.extend({}, $.fn.imageUpload.defaults, option || {});
    14. var target = $(this);
    15. var id = target.attr("id");
    16. var inputFileId = id + "_file";
    17. var html = '';
    18. html += '
      ';
    19. html += '
      ';
    20. html += '
      ';
    21. if (_option.canAdd == 1) {
    22. html += ' context + 'lib/imageupload/1.0/img/add.png" class="add-img">';
    23. deleteDisplay = 'block';
    24. }
    25. /**
    26. * 旧版本代码
    27. */
    28. //html += '
      // + '" class="file-image" callback="' + _option.uploadImage + '" context="'
    29. // + _option.context + '" limit="' + _option.limit
    30. // + '" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" />';
    31. /**
    32. * 20231024修改
    33. * 为input元素增加multiple属性
    34. */
    35. html += ' '" id="' + inputFileId
    36. + '" class="file-image" callback="' + _option.uploadImage + '" context="'
    37. + _option.context + '" multiple limit="' + _option.limit
    38. + '" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" />';
    39. html += ' ';
    40. 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);
  •  页面代码,替换原有页面初始化和自定义上传触发方法

    1. //初始化组件方法
    2. $("#thumbImage").imageUpload({ uploadImage: 'uploadThumbImage', limit: 10, context: ctx });//limit参数,设置单次上传和总上传数量
    3. function uploadThumbImage(file, callback) {//自定义的上传触发方法
    4. var formdata = new FormData();
    5. //formdata.append("fileList", file);//file为单文件数据(File类型)
    6. console.log('uploadThumbImage', file)
    7. for (var i = 0; i < file.length; i++) {//file为多文件数据(FileList类型)
    8. formdata.append("fileList", file[i]);//手动给formdata中添加文件流内容
    9. }
    10. ys.ajaxUploadFile({
    11. //url: '@GlobalContext.SystemConfig.ApiSite' + '/File/UploadFile?fileModule=@UploadFileType.News.ParseToInt()',
    12. url: '@Url.Content("~/File/uploadImagesProc")' + "?fileModule=@UploadFileType.News.ParseToInt()",
    13. data: formdata,
    14. success: function (obj) {
    15. if (obj.Tag == 1) {
    16. if (callback) {
    17. //callback('@GlobalContext.SystemConfig.ApiSite' + obj.Data);
    18. callback(obj.Data);
    19. }
    20. }
    21. else {
    22. ys.msgError(obj.Message);
    23. }
    24. }
    25. })
    26. }

    后台代码,可直接复制,UploadFileProc方法需在FileHelper类中创建

    1. ///
    2. /// 单/多文件上传
    3. ///
    4. ///
    5. ///
    6. [HttpPost]
    7. public async Taskobject>> uploadImagesProc(int fileModule, IFormFileCollection fileList)
    8. {
    9. TData<object> obj = new TData<object>();
    10. obj = await FileHelper.UploadFileProc(fileModule, fileList);
    11. return obj;
    12. }
    13. #region 上传多个文件
    14. ///
    15. /// 上传多个文件
    16. ///
    17. ///
    18. /// 文件流集合
    19. ///
    20. public async static Taskobject>> UploadFileProc(int fileModule, IFormFileCollection files)
    21. {
    22. string dirModule = string.Empty;
    23. TData<object> obj = new TData<object>();
    24. if (files == null || files.Count == 0)
    25. {
    26. obj.Message = "请先选择文件!";
    27. return obj;
    28. }
    29. //IFormFile file = files[0];
    30. List<object> resultObj = new List<object>();
    31. foreach (IFormFile file in files)
    32. {
    33. TData objCheck = null;
    34. objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png");
    35. if (objCheck.Tag != 1)
    36. {
    37. obj.Tag = 0;
    38. obj.Message = objCheck.Message;
    39. return obj;
    40. }
    41. switch (fileModule)
    42. {
    43. case (int)UploadFileType.Portrait:
    44. objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png");
    45. if (objCheck.Tag != 1)
    46. {
    47. obj.Message = objCheck.Message;
    48. return obj;
    49. }
    50. dirModule = UploadFileType.Portrait.ToString();
    51. break;
    52. case (int)UploadFileType.News:
    53. if (file.Length > 5 * 1024 * 1024) // 5MB
    54. {
    55. obj.Message = "文件最大限制为 5MB";
    56. return obj;
    57. }
    58. objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".jpg|.jpeg|.gif|.png");
    59. if (objCheck.Tag != 1)
    60. {
    61. obj.Message = objCheck.Message;
    62. return obj;
    63. }
    64. dirModule = UploadFileType.News.ToString();
    65. break;
    66. case (int)UploadFileType.Import:
    67. objCheck = CheckFileExtension(Path.GetExtension(file.FileName), ".xls|.xlsx");
    68. if (objCheck.Tag != 1)
    69. {
    70. obj.Message = objCheck.Message;
    71. return obj;
    72. }
    73. dirModule = UploadFileType.Import.ToString();
    74. break;
    75. default:
    76. obj.Message = "请指定上传到的模块";
    77. return obj;
    78. }
    79. string fileExtension = TextHelper.GetCustomValue(Path.GetExtension(file.FileName), ".png");
    80. string newFileName = SecurityHelper.GetGuid() + fileExtension;
    81. string dir = "Resource" + Path.DirectorySeparatorChar + dirModule + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd").Replace('-', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
    82. string absoluteDir = Path.Combine(GlobalContext.HostingEnvironment.ContentRootPath, dir);
    83. string absoluteFileName = string.Empty;
    84. if (!Directory.Exists(absoluteDir))
    85. {
    86. Directory.CreateDirectory(absoluteDir);
    87. }
    88. absoluteFileName = absoluteDir + newFileName;
    89. try
    90. {
    91. using (FileStream fs = System.IO.File.Create(absoluteFileName))
    92. {
    93. await file.CopyToAsync(fs);
    94. fs.Flush();
    95. }
    96. resultObj.Add(Path.AltDirectorySeparatorChar + ConvertDirectoryToHttp(dir) + newFileName);
    97. //obj.Data = ;
    98. //obj.Message = Path.GetFileNameWithoutExtension(TextHelper.GetCustomValue(file.FileName, newFileName));
    99. //obj.Description = (file.Length / 1024).ToString(); // KB
    100. //obj.Tag = 1;
    101. }
    102. catch (Exception ex)
    103. {
    104. obj.Tag = 0;
    105. obj.Message = ex.Message;
    106. }
    107. }
    108. if (resultObj.Count > 0)
    109. {
    110. obj.Tag = 1;
    111. obj.Message = "上传成功";
    112. obj.Data = resultObj;
    113. }
    114. return obj;
    115. }
    116. #endregion
    117. public static string ConvertDirectoryToHttp(string directory)
    118. {
    119. directory = directory.ParseToString();
    120. directory = directory.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
    121. return directory;
    122. }
    123. public static TData CheckFileExtension(string fileExtension, string allowExtension)
    124. {
    125. TData obj = new TData();
    126. string[] allowArr = TextHelper.SplitToArray<string>(allowExtension.ToLower(), '|');
    127. if (allowArr.Where(p => p.Trim() == fileExtension.ParseToString().ToLower()).Any())
    128. {
    129. obj.Tag = 1;
    130. }
    131. else
    132. {
    133. obj.Message = "只有文件扩展名是 " + allowExtension + " 的文件才能上传";
    134. }
    135. return obj;
    136. }
    137. public class TextHelper
    138. {
    139. ///
    140. /// 获取默认值
    141. ///
    142. ///
    143. ///
    144. ///
    145. public static string GetCustomValue(string value, string defaultValue)
    146. {
    147. if (string.IsNullOrEmpty(value))
    148. {
    149. return defaultValue;
    150. }
    151. else
    152. {
    153. return value;
    154. }
    155. }
    156. ///
    157. /// 截取指定长度的字符串
    158. ///
    159. ///
    160. ///
    161. ///
    162. public static string GetSubString(string value, int length, bool ellipsis = false)
    163. {
    164. if (string.IsNullOrEmpty(value))
    165. {
    166. return value;
    167. }
    168. if (value.Length > length)
    169. {
    170. value = value.Substring(0, length);
    171. if (ellipsis)
    172. {
    173. value += "...";
    174. }
    175. }
    176. return value;
    177. }
    178. ///
    179. /// 字符串转指定类型数组
    180. ///
    181. ///
    182. ///
    183. ///
    184. public static T[] SplitToArray<T>(string value, char split)
    185. {
    186. T[] arr = value.Split(new string[] { split.ToString() }, StringSplitOptions.RemoveEmptyEntries).CastSuper().ToArray();
    187. return arr;
    188. }
    189. }

     

  • 相关阅读:
    面试必问:JVM 如何确定死亡对象?
    day13面向对象进阶
    【Postman】Postman+国密SM2+https协议+Api接口获取sign和token解决方法(特定项目参照用,莫照搬)
    oninput和onchange事件有什么区别以及使用场景
    重上吹麻滩——段芝堂创始人翟立冬游记
    Kubernetes学习笔记-StatefulSet:部署有状态的多副本应用(1)20220624
    Go十大常见错误第9篇:使用文件名称作为函数输入
    随想录一刷Day44——动态规划
    干货分享!使用 Cocos 在可视化领域蓝海掘金!
    首个828 B2B企业节:华为携手生态伙伴,赋能中小企业数字化转型
  • 原文地址:https://blog.csdn.net/MoFe1/article/details/134005257