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

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

将完整的图片上传流程进行整理

html代码

<tr>
	<td style="padding-left: 5px">
		<label>医生照片:</label>
	</td>		
	<td colspan="2" style="padding-left: 5px"> 
		<input type="file" id="uploadMyImg" name="uploadMyImg" accept="image/jpg"/>
		<div id="fileSize">
		</div>
		<div>
			<span>图片仅支持不超过20kb的jpg格式</span>
		</div>
	</td>
	<td align="left" style="padding-left: 0px" style="padding-left: 5px">
		<img id="showUrl" src="" style="width:140px;height:80px;" />
	</td>	
</tr>

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 src = "";
                    var obj = $("#showUrl");
                    var div = obj.parent("div")[0];
                    _self.select();
                    if (top != self) {
                        window.parent.document.body.focus()
                    } else {
                        _self.blur()
                    }
                    src = 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 = 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) {
        Map <String, Object> map = new HashMap <String, Object> ();
        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 ();
    }
/**
     * <p>
     * 原来方法提取出来,修改图片名称,使用编码作为存图名字
     */
    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;





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值