通过修改ajaxFileUpload.js实现多图片动态上传并实现预览
通过修改ajaxFileUpload.js实现多图片动态上传并实现预览
大部分我也是根据他的方法修改的,我也要根据name实现动态的多文件上传功能,但是有个问题使我一直无法实现多文件上传。
就是我发现上传到后台的文件的数目是你要上传数量的平方。找了很久才发现这是因为他的代码还是有点小问题:
前段时间做项目有个一个实现多文件上传的功能,因为以前也没有接触过,于是花了好几天时间才给弄好了,但是回头一看也没什么,咋就花了那么长时间呢,看来自己的效率有待提高啊。axFileUpload.js里面的代码修改一下就能支持多个Id同时上传,把源码中的这个:
if (typeof (fileElementId) == 'string') {fileElementId = [fileElementId];}for (var i in fileElementId) {//按name取值var oldElement = jQuery("input[name=" + fileElementId[i] + "]");oldElement.each(function () {var newElement = jQuery($(this)).clone();jQuery(oldElement).attr('id', fileId);//只将旧元素的Id修改,没有修改name jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);});}
因为是按name上传,那么我们需要把原页面中的name属性给修改掉,再加一行就ok了:
if (typeof (fileElementId) == 'string') {fileElementId = [fileElementId];}for (var i in fileElementId) {//按name取值var oldElement = jQuery("input[name=" + fileElementId[i] + "]");oldElement.each(function () {var newElement = jQuery($(this)).clone();//jQuery(this).attr('id', fileId);jQuery(this).attr('name', fileId);jQuery(this).before(newElement);jQuery(this).appendTo(form);});}
,这样就能实现根据name动态多文件上传了。
页面代码如下:
<body style="background: #FFFFFF;"><form action="/Home/UploadImage" id="form1" name="form1" method="post"><table style="width: 100%" class="SubTable"><tbody><tr class="tr"><td style="width: 80%"><input name="upload" type="file" onchange="IsRepeat(this)" style="width: 100%" /></td><td style="width: 20%"><input type="button" value="删除" onclick="deletefile(this, 4)" /></td></tr><tr class="footTr"><td colspan="2"><input type="button" value="添加" onclick="addfile(this, 4)" /></td></tr><tr><td style="text-align: center" colspan="2"><input type="button" value="提交" id="BtnSub" /></td></tr></tbody></table><table><tr><td style="height: 130px; width: 18%">图片预览:</td><td style="height: 130px; width: 82%"><table style="width: 100%" class="SubTable"><tbody><tr class="tr"><td><div id="trimagedivBef" style="display: none"></div></td><td style="width: 25%"><input style="width: 100px; height: 80px; display: none" type="image"></td><td style="width: 25%"><input style="width: 100px; height: 80px; display: none" type="image"></td><td style="width: 25%"><input style="width: 100px; height: 80px; display: none" type="image"></td><td style="width: 25%"><input style="width: 100px; height: 80px; display: none" type="image"></td><td><div id="trimagedivAft" style="display: none"></div></td></tr><tr class="footer"><td><div id="footerimagedivBef" style="display: none"></div></td><td class='footertd' style="width: 25%"><div style="display: none"><a href="#">删除</a></div></td><td class='footertd' style="width: 25%"><div style="display: none"><a href="#">删除</a></div></td><td class='footertd' style="width: 25%"><div style="display: none"><a href="#">删除</a></div></td><td class='footertd' style="width: 25%"><div style="display: none"><a href="#">删除</a></div></td><td style="text-align: center"><div id="footerimagedivAft" style="display: none"></div></td></tr></tbody></table></td></tr></table></form> </body>
js代码,上传成功后要实现预览功能,如果不考虑安全因素的话直接获取图片保存在的路径就行,但是这样是肯定不被允许的,太不安全,于是把文件放到一个指定的文件夹下
后再通过一个action获取该图片的路径:
<script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/js/ajaxfileupload.js"></script> <script type="text/javascript">function IsRepeat(obj) {var filters = "jpg png bmp";var val = $(obj).val();var arr = val.split('.');if (filters.indexOf(arr[arr.length - 1]) < 0) {$(obj).val("");alert("请上传 " + filters + " 格式的图片", "提示");return;}var count = 0;$("input[name='upload']").each(function () {if ($(this).val()) {if ($(this).val() == val) {if (count >= 1) {$(this).val("");alert("已上传该图片,请重新选择!", "提示");return;}count++;}}})}function deleteImage(val) {if (confirm("是否删除图片?")) {falg = false;var id = "#del_" + val;$(id).parent().remove();id = "#image_" + val;$(id).parent().remove();$("#trimagedivAft").closest("td").before("<td style=\"width:25%\"><input style=\"width:100px;height:80px;display:none\" type=\"image\" src=\"#\"></td>");$("#footerimagedivAft").closest("td").before("<td class='footertd' style=\"text-align:center;width:25%\"><div style=\"display:none\"><a href=\"#\">删除</a></div></td>");}}function addfile(obj, maxNum) {$(obj).closest("tr").before(" <tr class=\"tr\"><td width=\"80%\"><input name=\"upload\" type=\"file\" οnchange=\"IsRepeat(this)\" style=\"width:100%;\" /></td><td width=\"20%\"><input type=\"button\" value=\"删除\" οnclick=\"deletefile(this," + maxNum + ");\" /> </td></tr>");//检测是否已经到达最大的个数,需要隐藏添加按钮if (maxNum > 0) {if ($(obj).closest("table").children().children(".tr").length == maxNum) {$(obj).hide();}}return false;}function deletefile(obj, maxNum) {//检测是否已经到达最大的个数,需要隐藏添加按钮if (maxNum > 0) {var inputAdd = $(obj).closest("table").children().children(".footTr").children().children("input");var num = $(obj).closest("table").children().children(".tr").length;$(obj).closest("tr").remove();if ((num - 1) < maxNum) {inputAdd.show(); //定位到添加按钮 }}else {$(obj).closest("tr").remove();}return false;}var falg = false;var countFalg = 0;$("#BtnSub").click(function () {var falg = true;$("input[name='upload']").each(function () {if ($(this).val() == "") {falg = false;}})if (!falg) {alert("上传图片不能为空", "提示");return;}$.ajaxFileUpload({url: "@Url.Action("PhotoUploadImage", "Home")",secureuri: false,fileElementId: 'upload',//修改了ajaxFileUpload.js源码,支持上传多个name相同的文件,修改处在45行~57行dataType: 'json',success: function (data, status) {//alert(data['status'] + '-----' + data['fileName'] + '-----' + data['extName']);if (data != null) {var returnValue = data['filePath'];if (returnValue) {var array = returnValue.split('|');var retLen = array.length;var ss = "";for (var i = 0; i < array.length; i++) {if (array[i]) {var len = $("#trimagedivAft").closest("tr").children(".td").length;var ran = Math.ceil(Math.random() * 9999999999999999);var fp = "";fp = "@Url.Action("ShowImage", "Home")" + "?filePath=" + array[i].split(',')[0];if (!falg) {$("#trimagedivAft").parent().prev().remove();$("#footerimagedivAft").parent().prev().remove();$("#trimagedivBef").closest("td").after("<td class='td' style=\"width:25%\"><input width='100px' id='image_" + ran + "' height='80px' value=" + array[i] + " src=" + fp + " type=\"image\"/></td>");$("#footerimagedivBef").closest("td").after("<td class='footertd' style=\"text-align:center;width:25%\"><div οnclick='deleteImage(" + ran + ")' id='del_" + ran + "'><a href=\"#\">删除</a></div></td>");} else {$("#trimagedivBef").parent().next().remove();$("#footerimagedivBef").parent().next().remove();$("#trimagedivAft").closest("td").before("<td class='td' style=\"width:25%\"><input width='100px' id='image_" + ran + "' height='80px' value=" + array[i] + " src=" + fp + " type=\"image\"/></td>");$("#footerimagedivAft").closest("td").before("<td class='footertd' style=\"text-align:center;width:25%\"><div οnclick='deleteImage(" + ran + ")' id='del_" + ran + "'><a href=\"#\">删除</a></div></td>");}countFalg++;if (countFalg >= 4) {falg = true;}}}}}},error: function (data, status, e) {//alert(e);alert("上传失败");return false;}})}) </script>
后台上传代码:
//上传附件public void PhotoUploadImage(object sender, EventArgs e){var files = Request.Files;DateTime now = DateTime.Now;string time = DateTime.Now.ToString("yyyy-MM");string tmpPath = Server.MapPath("~/App_Data/upload/images/" + time);string filesPathArr = "";if (files != null && files.Count > 0){for (int i = 0; i < files.Count; i++){var file = files[i];if (Directory.Exists(tmpPath) == false)//如果不存在就创建file文件夹 {Directory.CreateDirectory(tmpPath);}double fileSize = file.ContentLength;Thread.Sleep(10);string name = Path.GetFileNameWithoutExtension(file.FileName);string extName = Path.GetExtension(file.FileName);string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfffff") + extName;try{string filePath = tmpPath + "/" + fileName;file.SaveAs(filePath);filesPathArr += "/App_Data/upload/images/" + time + "/" + fileName + "," + fileSize + "," + name + "," + extName + "|";}catch (Exception ex){Response.Write(@"{status : 'error',msg : '" + ex.Message + @"'}");Response.End();return;}}}Response.Write(@"{status : 'success', msg: { Origin : ''},filePath:'" + filesPathArr + @"'}");}
获取上传图片路径的代码:
public ActionResult ShowImage(string filePath = ""){string path = Server.MapPath("~" + filePath);return base.File(path, "Image/jpeg");}