上传图片(图片路径和图片本身都进行保存)

上传图片(图片路径和图片本身都进行保存) 将完整的图片上传流程进行整理
html代码

图片仅支持不超过20kb的jpg格式 上传图片(图片路径和图片本身都进行保存)
文章图片

js代码
对于图片格式,大小进行判定
$("body").delegate("#uploadMyImg", "change", function (e) { fileChange(e.target); });

//校验图片类型和大小 var isIE = /msie/i.test(navigator.userAgent) && !window.opera; var sizeLabel = ["B", "KB", "MB", "GB"]; function fileChange(target) { var filepath = target.value; if(filepath){ var fileend = filepath.substring(filepath.indexOf(".")); if(".jpg" != fileend){ $.messager.alert('提示', "只能接受jpg类型的图片!", 'info'); target.value =""; return false; } } if (isIE && !target.files) { var filePath = target.value; var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); if(!fileSystem.FileExists(filePath)){ $.messager.alert('提示', "图片不存在,请重新上传!", 'info'); return false; } var file = fileSystem.GetFile (filePath); fileSize = file.Size; } else { fileSize = target.files[0].size; } //显示图片大小 displayFileSize(fileSize); $("#fileSize").show(); //判断图片大小不能超过20KB if(fileSize > 20480){ $.messager.alert('提示', "图片大小不能超过20KB!", 'info'); target.value =""; var fileSize = document.getElementById("fileSize"); fileSize.innerHTML = ''; return false; } else{ var _self = this; _self.getObjectURL = function (file) { var url = null; if (window.createObjectURL != undefined) { url = window.createObjectURL(file) } else if (window.URL != undefined) { url = window.URL.createObjectURL(file) } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file) } return url }; if (target.value) { try { $("#showUrl").attr('src', _self.getObjectURL(target.files[0])) $("#showUrl").show(); } catch (e) { var srchttps://www.it610.com/article/= ""; var obj = $("#showUrl"); var div = obj.parent("div")[0]; _self.select(); if (top != self) { window.parent.document.body.focus() } else { _self.blur() } src = https://www.it610.com/article/document.selection.createRange().text; document.selection.empty(); obj.hide(); obj.parent("div").css({ 'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)', 'width': '120px', 'height':'100px' }); div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = https://www.it610.com/article/src; $("#showUrl").show(); } } else { $("#showUrl").attr('src', _self.getObjectURL(target.files[0])); $("#showUrl").show(); } } }function displayFileSize(size) { var fileSize = document.getElementById("fileSize"); fileSize.innerHTML = calFileSize(size); }function calFileSize(size) { for (var index = 0; index < sizeLabel.length; index++) { if (size < 1024) { return round(size, 2) + sizeLabel[index]; } size = size / 1024; } return round(size, 2) + sizeLabel[index]; }function round(number, count) { return Math.round(number * Math.pow(10, count)) / Math.pow(10, count); }

新增弹框请空图片路径
$("#showUrl").attr("src",""); $("#showUrl").hide(); $("#fileSize").empty(); $("#fileSize").hide();

修改弹框显示图片
if (null != row.imageUrl && '' != row.imageUrl ) { $("#showUrl").attr("src",row.imageUrl); $("#showUrl").show(); } else{ $("#showUrl").hide(); } $("#fileSize").empty(); $("#fileSize").show();

保存使用easyui的from表单提交
controller代码
【上传图片(图片路径和图片本身都进行保存)】controller中使用@ModelAttribute的形式进行接值
@RequestMapping ("/saveCommodity") @ResponseBody public String saveCommodity (HttpServletRequest request, HttpServletResponse response, @ModelAttribute ("commodityForm") Commodity commodity) { Mapmap = new HashMap(); boolean success = Boolean.TRUE; String idsStr = request.getParameter ("id"); long id = 0; if (StringUtils.isNotEmpty (idsStr)) { id = Long.parseLong (idsStr); } try { // 图片处理 if (null != commodity.getUploadMyImg ().getOriginalFilename() && "" != commodity.getUploadMyImg ().getOriginalFilename ()) { imgHandler (commodity); } if (id != 0) { commodity.setId (id); commodity.setUpdateTime (new Date ()); _commodityService.updateCommodity (commodity); }else{ commodity.setStatus ("0"); commodity.setCreateTime (new Date ()); commodity.setUpdateTime (new Date ()); _commodityService.addCommodity (commodity); } } catch (Exception ex) { _logger.error ("保存商品类型失败" + ex); map.put ("message", "保存商品类型失败"); success = Boolean.FALSE; }map.put ("success", success); return JSONObject.fromObject (map).toString (); }

/** * * 原来方法提取出来,修改图片名称,使用编码作为存图名字 */ private void imgHandler (Commodity commodity) { String orgCodePath ="commodity"; File fileOrgCode = new File (orgCodePath); if (!fileOrgCode.exists ()) { fileOrgCode.mkdirs (); }String deptCodePath = orgCodePath + File.separator + (fdpDoctor.getDocCode () == null ? "null" : fdpDoctor.getDocCode ()); File fileDeptCode = new File (deptCodePath); if (!fileDeptCode.exists ()) { fileDeptCode.mkdirs (); }String fileName = fdpDoctor.getUploadMyImg ().getOriginalFilename (); fdpDoctor.setLogoPath (fdpDoctor.getUploadMyImg ().getOriginalFilename ()); if (fdpDoctor.getDocCode () != null) { fileName = fdpDoctor.getDocCode ().replaceAll ("//", "").replaceAll ("\\\\", "") + fileName.substring (fileName.lastIndexOf (".")); } String orgPath = deptCodePath + File.separator + fileName; fdpDoctor.setLogoPath (orgPath); String path = PropertiesUtils.getProperties ("fdp", "fdp.image.realpath"); //此为读取配置文件中的路劲地址 String imgPath = path + File.separator + orgPath; File fileSave = new File (imgPath); if (!fileSave.exists ()) { fileSave.mkdirs (); } try { byte[] bytes = FileCopyUtils.copyToByteArray (commodity.getUploadMyImg ().getInputStream ()); commodity.setCommodityImage (bytes); commodity.getUploadMyImg ().transferTo (fileSave); } catch (IllegalStateException e1) { _logger.error ("图片上传异常!" + e1.getMessage ()); e1.printStackTrace (); } catch (IOException e1) { _logger.error ("图片上传异常!" + e1.getMessage ()); e1.printStackTrace (); } }

查询所有数据时,将图片路径存储到实体类中,方便前端直接取用
if (null != fdpDoctor1.getLogoPath () && "" != fdpDoctor1.getLogoPath ()) { String path = PropertiesUtils.getProperties ("fdp", "fdp.image.uri"); //此为读取配置文件中的路劲地址 String imageUrl = path + fdpDoctor1.getLogoPath (); fdpDoctor1.setImageUrl (imageUrl); }

实体类中有关图片存储的字段
/** * 商品图片(二进制) */ private byte[] _commodityImage; /** * 商品图片(地址) */ private String _commodityImagePath; private MultipartFile uploadMyImg; /** * 图片虚拟访问地址 */ private String imageUrl;







    推荐阅读