文件上传控件bootstrap-fileinput的使用
1.插件下载地址:https://github.com/kartik-v/bootstrap-fileinput
2.插件的引用
需要引用jquery
需要结合bootstrap使用,即页面需要引入bootstrap相关js和css文件
引用fileinput.js 和css
中文需要引用js/locales/zh.js
需要主题样式时引用themes下相关文件夹中的js和css
tips:最好以上按顺序引用,免得出现莫名其妙的问题,比如zh.js必须在fileinput.js后引用否则无效
3.插件的代码部分
<form id="frmUpload" method="post" enctype="multipart/form-data"> <input id="input-id" type="file" class="file-loading" accept="image/*,.pdf,.xls,.xlsx,.docx,.doc" /> </form>
js代码初始化
$("#input-id").fileinput({ theme: 'zh', uploadUrl: _uploadUrl, // 上传的地址 language: 'zh', //设置语言 showCaption: false, //是否显示标题 uploadClass: "btn btn-default rightBtn", //showUpload: _showUp,//是否显示上传按钮 showRemove: false, //是否显示删除按钮 showPreview: true, //是否显示文件的预览图 overwriteInitial: false, //不覆盖已存在的图片 initialPreviewShowDelete: true, showClose: true, //是否显示删除按钮 autoReplace: true, //再次选择,覆盖之前图片内容 //minImageWidth: 400, //图片的最小宽度 //minImageHeight: 400,//图片的最小高度 //maxImageWidth: 800,//图片的最大宽度 //maxImageHeight: 800,//图片的最大高度 previewSettings: {//预览图片大小设置 image: { width: "5000px", height: "500px" } }, browseClass: "btn btn-primary rightBtn", //按钮样式 maxFileCount: 2,//允许最大上传文件的数量 minFileCount: 0,//允许最大上传文件的数量 allowedFileExtensions: "image/*,.pdf,.xls,.xlsx,.docx,.doc", //接收的文件后缀 uploadAsync: false,//上传异步 uploadExtraData: function () { return { paraA: vaule }; //上传时额外附加参数 }, initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup initialPreviewFileType: 'image', //初始化时预览文件类型 initialPreview: _initialPreview,//初始化时显示已有数据 initialPreviewDownloadUrl: _initialPreviewDownloadUrl, // 初始化预览下载地址 initialPreviewConfig: { caption: '555', // 展示的文件名 width: '120px', style: 'max-width:100%;max-height:100%;', downloadurl: "", // 下载url key: "id", // 删除是Ajax向后台传递的参数, type: 'image' // 预览文件类型 },//初始化时config fileActionSettings: { removeClass: 'hideBtn', downloadClass: 'hideBtn', uploadClass: 'hideBtn', zoomClass: 'hideBtn' }, deleteUrl: _deleteUrl,//删除地址 maxFileSize: "10240",//最大容量 msgSizeTooLarge: "文件 '{name}' (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.", initialCaption: "The photo" }).on("filebatchuploadsuccess", function (event, d) { //上传成功后回调函数 var form = d.form, files = d.files, extra = d.extra, response = d.response, reader = d.reader; }) .on('filedeleted', function (event, key) { if (event.handleObj.handler.arguments[2].responseJSON.success) { } else { wxc.xcConfirm("删除失败!", wxc.xcConfirm.typeEnum.info); } }) .on('filebatchselected', function (event, files) { var _maxRequestSize = 10240; _allFileSize = 0; $.each(files, function (idx, item) { _allFileSize += (item.size / 1024); }); _allFileSize = parseFloat(_allFileSize.toFixed(2)); if (_allFileSize > _maxRequestSize) { var msg = "选择的文件总大小(" + (_allFileSize / 1024).toFixed(2) + "MB)超出限制(" + (_maxRequestSize / 1024).toFixed(2) + "MB)"; $('#input-id').fileinput('clear'); alert(msg); } }) .on('filebatchuploaderror', function (event, data, msg) { var _maxRequestSize = 10240; _allFileSize = 0; if (_allFileSize > _maxRequestSize) { msg = "上传文件总大小(" + (_allFileSize / 1024).toFixed(2) + "MB)超出限制(" + (_maxRequestSize / 1024).toFixed(2) + "MB)"; $('#input-id').fileinput('clear'); alert(msg); } });
4.插件的部分属性说明
1.multiple表示允许同时上传多个文件,class=“file-loading”表示标签的样式。这里很重要,如果class="file",则中文化不能生效。
2.accept 属性只能与 <input type="file"> 配合使用。它规定能够通过文件上传进行提交的文件类型。这个属性和插件allowedFileExtensions属性看起来一样但是插件的
allowedFileExtensions属性只是你选择了文件类型之后他会提示你禁止上传,如图
而accept 属性则是在点击选择文件之后,文件框里只会出现你写在accept 属性的后缀名的文件.可以在一开始就避免用户选择错误的文件类型,当然如果直接拖进控件,那
也是没有办法,如图:
这张是没有加accept 属性
这张是加了accept="image/*,.pdf,.xls,.xlsx,.docx,.doc"的图片
3.部分要使用的方法
.on("filebatchuploadsuccess", function (event, d) { //上传成功后回调函数 var form = d.form, files = d.files, extra = d.extra, response = d.response, reader = d.reader; }) .on('filedeleted', function (event, key) {//删除后回调函数 if (event.handleObj.handler.arguments[2].responseJSON.success) { alert("上传成功!") } else { aler("删除失败!"); } }) .on('filebatchselected', function (event, files) {//批量选择后回调函数 var _maxRequestSize = 10240; _allFileSize = 0; $.each(files, function (idx, item) { _allFileSize += (item.size / 1024); }); _allFileSize = parseFloat(_allFileSize.toFixed(2)); if (_allFileSize > _maxRequestSize) { var msg = "选择的文件总大小(" + (_allFileSize / 1024).toFixed(2) + "MB)超出限制(" + (_maxRequestSize / 1024).toFixed(2) + "MB)"; $('#input-id').fileinput('clear'); alert(msg); } }) .on('filebatchuploaderror', function (event, data, msg) {//批量上传失败提示 var _maxRequestSize = 10240; _allFileSize = 0; if (_allFileSize > _maxRequestSize) { msg = "上传文件总大小(" + (_allFileSize / 1024).toFixed(2) + "MB)超出限制(" + (_maxRequestSize / 1024).toFixed(2) + "MB)"; $('#input-id').fileinput('clear'); alert(msg); } });
4.有的想去除掉控件中的一些按钮,如图
showUpload,showRemove属性是是否显示红色的部分的移除,上传按钮是否显示.
而黑色部分按钮的隐藏显示则是由fileActionSettings这个属性来决定的
具体的内容请看http://plugins.krajee.com/file-input/plugin-options#fileActionSettings
写一个class内容为display:none;然后把这个class赋值给对应的属性就ok了.如图
效果如第三张图,图片右下角删除按钮已被禁用掉.
5.Controller中的代码
简易版:
[HttpPost] public ActionResult UploadImages() { var _files = Request.Files;//获取上传的文件 var _paraA = Request["paraA"];//获取上传文件时附加的参数 var _imgList = new List<string>();//用于存储已上传图片,无刷新时显示 var _lstInitialPreview = new List<string>();//初始化 var _lstInitialPreviewConfig = new List<dynamic>();//初始化配置 //todo 可将文件存储至指定位置,并将文件相关信息保存至数据库 /*此处需要遵循 bootstrap的 fileinput 格式回传 */ return Json(new { success = false, d = _imgList, initialPreview = _lstInitialPreview, initialPreviewConfig = _lstInitialPreviewConfig }); }
我的代码,可能有不足之处
private static readonly object m_locker = new object(); /// <summary> /// 上传图片 /// </summary> /// <returns></returns> [HttpPost] public ActionResult UploadImages() { var _files = Request.Files;//上传的所有文件 var _relatedType = Request["RelatedType"];//图片关联的表 var _relatedId = int.Parse(Request["RelatedId"]);//图片关联表的Id var _imageType = (ImageUsageCodeEnum)int.Parse(Request["ImageType"]);//图片的枚举,用于上传到指定地址后增加一个文件区分 var _imgList = new List<string>();//用于存储已上传图片,无刷新时显示 var _lstInitialPreview = new List<string>();//图片预览初始化 var _lstInitialPreviewConfig = new List<dynamic>();//图片预览初始化配置 var _imgUrl = $"{SiteHelper.RESOURCE_PATH}/images/";//图片上传到的地址, //我存储的方式是 $"{_imgUrl}/{_imageType}/{_newFileName}" 上传文件统一地址 +/images/ + 图片类型 + 重新生成的唯一文件名称 #region 创建目录 m_logger.Info("Config Image Path:{0}", SiteHelper.UploadPath); var _directory = $@"{SiteHelper.UploadPath}\images\{_imageType.ToString()}";
m_logger.Info("Upload Image Path:{0}", _directory); //var _directory = "D:\\images"; try { if (!Directory.Exists(_directory)) { lock (m_locker) { if (!Directory.Exists(_directory)) { Directory.CreateDirectory(_directory); } } } } catch (Exception ex) { m_logger_err.Error("不能创建上传文件的目录:{0}, 详细信息:{1}", _directory, ex.Message + " - " + ex.StackTrace.ToString()); return Json(new ApiResponseMsg { err_msg = string.Format("不能创建上传文件的目录:{0}", _directory) }, JsonRequestBehavior.AllowGet); } #endregion #region 上传文件 / 保存到数据库 var msg = ""; //用于获取文件后缀 Func<string, string> getType = (ext) => { ext = ext.Replace(".", ""); if (Regex.IsMatch(ext, "(gif|png|jpe?g)$")) { return "image"; } else if (Regex.IsMatch(ext, "(htm|html)$")) { return "html"; } else if (Regex.IsMatch(ext, "(rtf|docx?|xlsx?|pptx?|pps|potx?|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$")) { return "office"; } else if (Regex.IsMatch(ext, "(txt|md|csv|nfo|ini|json|php|js|css)$")) { return "text"; } else if (Regex.IsMatch(ext, "(og?|mp4|webm|mp?g|mov|3gp)$")) { return "video"; } else if (Regex.IsMatch(ext, "(og?|mp3|mp?g|wav)$")) { return "audio"; } else if (Regex.IsMatch(ext, "(swf)$")) { return "flash"; } else if (Regex.IsMatch(ext, "(pdf)$")) { return "pdf"; } return "audio"; }; //循环所有的文件 for (int i = 0; i < _files.Count; i++) { if (_files[i].ContentLength > 0) { var _fileName = _files[i].FileName;//文件名 var _extension = _fileName.Substring(_fileName.LastIndexOf('.'));//文件后缀 var _newFileName = Guid.NewGuid().ToString("N") + _extension;//为文件新命名一个guid名字,避免用户上传的的文件同名 _files[i].SaveAs(Path.Combine(_directory, _newFileName));//保存至指定地址 #region 新图片数据库Add Modeles.Image _image = new Modeles.Image { CreatedBy = UserId, CreatedOn = DateTime.Now, Name = _fileName, ImageFileName = _newFileName, ImageUsageCode = (int)_imageType, ImageXrefList = new List<Models.ImageXref> { new Modeles.ImageXref { RelatedType = _relatedType, RelatedId = _relatedId, CreatedBy = UserId, CreatedOn = DateTime.UtcNow } } }; var _result = AddOrUpdate(_image, "Image/AddImage", false); if (!_result.success) { m_logger.Error("request error: {0}, url: {1}, data: {2}", _result.err_msg, _reqUrl, JsonConvert.SerializeObject(_image)); msg = "系统忙,请稍后再试"; break; } //我的图片展示的方式,可自定义 _imgList.Add($"{_imageType.ToString()}/{_newFileName}" + "|" + _fileName + "|" + _result.data); //我存储的方式是 $"{_imgUrl}/{_imageType}/{_newFileName}" 上传文件统一地址 + 图片类型 + 重新生成的唯一文件名称 var _downLoadUrl = $"{_imgUrl}{_imageType.ToString()}/{_newFileName}"; _lstInitialPreview.Add(_downLoadUrl);//下载地址 _lstInitialPreviewConfig.Add(new { downloadurl = _downLoadUrl,//下载地址 key = _result.data,//图片上传时新增至数据库对应记录的Id type = getType(_extension)//文件后缀 }); #endregion m_logger.Info("UploadImage save to db successed!"); } } #endregion if (msg != "") { return Json(new ApiResponseMsg { err_msg = msg }, JsonRequestBehavior.AllowGet); } /*此处需要遵循 bootstrap的 fileinput 格式回传 */ return Json(new { success = false, d = _imgList, initialPreview = _lstInitialPreview, initialPreviewConfig = _lstInitialPreviewConfig }); }
6.图片转换
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Utilities.Helper { /// <summary> /// image帮助类 /// </summary> public static class ImageHelper { /// <summary> /// Convert Image to Byte[] /// </summary> /// <param name="image">图形对象</param> /// <returns></returns> public static byte[] ImageToBytes(Image image) { ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { if (format.Equals(ImageFormat.Jpeg)) { image.Save(ms, ImageFormat.Jpeg); } else if (format.Equals(ImageFormat.Png)) { image.Save(ms, ImageFormat.Png); } else if (format.Equals(ImageFormat.Bmp)) { image.Save(ms, ImageFormat.Bmp); } else if (format.Equals(ImageFormat.Gif)) { image.Save(ms, ImageFormat.Gif); } else if (format.Equals(ImageFormat.Icon)) { image.Save(ms, ImageFormat.Icon); } else { image.Save(ms, ImageFormat.Jpeg); } byte[] buffer = new byte[ms.Length]; //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return buffer; } } /// <summary> /// Convert Byte[] to Image /// </summary> /// <param name="buffer">字节数组</param> /// <returns></returns> public static Image BytesToImage(byte[] buffer) { MemoryStream ms = new MemoryStream(buffer); Image image = System.Drawing.Image.FromStream(ms); return image; } /// <summary> /// Convert Byte[] to a picture and Store it in file /// </summary> /// <param name="fileName"></param> /// <param name="buffer"></param> /// <returns></returns> public static string CreateImageFromBytes(string fileName, byte[] buffer) { string file = fileName; Image image = BytesToImage(buffer); ImageFormat format = image.RawFormat; if (format.Equals(ImageFormat.Jpeg)) { file += ".jpeg"; } else if (format.Equals(ImageFormat.Png)) { file += ".png"; } else if (format.Equals(ImageFormat.Bmp)) { file += ".bmp"; } else if (format.Equals(ImageFormat.Gif)) { file += ".gif"; } else if (format.Equals(ImageFormat.Icon)) { file += ".icon"; } else { file += ".jpg"; } System.IO.FileInfo info = new System.IO.FileInfo(file); System.IO.Directory.CreateDirectory(info.Directory.FullName); File.WriteAllBytes(file, buffer); return file; } /// <summary> /// 压缩图片, 并保存释放图片 /// </summary> /// <param name="img"></param> /// <param name="dFile"></param> /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param> /// <returns></returns> public static bool ZipPic(Image img, string dFile, int flag) { ImageFormat tFormat = img.RawFormat; //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { img.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { img.Save(dFile, tFormat); } return true; } catch { return false; } finally { img.Dispose(); } } /// <summary> /// 按比例缩放图片 /// </summary> /// <param name="SourceImage">源图片,自动释放</param> /// <param name="TargetWidth"></param> /// <param name="TargetHeight"></param> /// <returns></returns> public static Image ZoomPicture(Image SourceImage, int TargetWidth, int TargetHeight) { int IntWidth; //新的图片宽 int IntHeight; //新的图片高 try { System.Drawing.Imaging.ImageFormat format = SourceImage.RawFormat; System.Drawing.Bitmap SaveImage = new System.Drawing.Bitmap(TargetWidth, TargetHeight); Graphics g = Graphics.FromImage(SaveImage); g.Clear(Color.White); if (SourceImage.Width > TargetWidth && SourceImage.Height <= TargetHeight)//宽度比目的图片宽度大,长度比目的图片长度小 { IntWidth = TargetWidth; IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width; } else if (SourceImage.Width <= TargetWidth && SourceImage.Height > TargetHeight)//宽度比目的图片宽度小,长度比目的图片长度大 { IntHeight = TargetHeight; IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height; } else if (SourceImage.Width <= TargetWidth && SourceImage.Height <= TargetHeight) //长宽比目的图片长宽都小 { IntHeight = SourceImage.Width; IntWidth = SourceImage.Height; } else//长宽比目的图片的长宽都大 { IntWidth = TargetWidth; IntHeight = (IntWidth * SourceImage.Height) / SourceImage.Width; if (IntHeight > TargetHeight)//重新计算 { IntHeight = TargetHeight; IntWidth = (IntHeight * SourceImage.Width) / SourceImage.Height; } } // g.DrawImage(SourceImage, (TargetWidth - IntWidth) / 2, (TargetHeight - IntHeight) / 2, IntWidth, IntHeight); g.DrawImage(SourceImage,0,0, TargetWidth, TargetHeight); SourceImage.Dispose(); return SaveImage; } catch (Exception ex) { } return null; } } }
此时就可已将byte形式的图片转化为图片格式并保存值至指定位置
ImageHelper.BytesToImage(bytes).Save(_directory + "/" + _newFileName);