上传图片的代码demo

来源:互联网 发布:古剑奇谭ol 知乎 编辑:程序博客网 时间:2024/05/16 00:29

html代码片段

                            <form action="insertProduct.do" class="form-horizontal" method="post" enctype="multipart/form-data">                                <div class="form-group">                                    <label class="col-sm-2 control-label">商品名称:</label>                                    <div class="col-sm-8">                                        <input type="text" class="form-control rounded" name="productName">                                    </div>                                </div>                                <div class="line line-dashed line-lg pull-in"></div>                                                               <div class="form-group">                                    <label class="col-sm-2 control-label">商品类型:</label>                                    <div class="col-sm-8">                                        <div class="row">                                            <div class="col-md-4">                                                <input type="text" class="form-control" name="productType" placeholder="商品大类">                                            </div>                                            <div class="col-md-4">                                                <input type="text" class="form-control" name="children" placeholder="商品大类">                                            </div>                                        </div>                                    </div>                                </div>                                <div class="line line-dashed line-lg pull-in"></div>                                                                <div class="form-group">                                    <label class="col-sm-2 control-label">商品原价:</label>                                    <div class="col-sm-4">                                        <input type="text" class="form-control" name="oldPrice">                                    </div>                                </div>                                <div class="form-group">                                    <label class="col-sm-2 control-label">商品现价:</label>                                    <div class="col-sm-4">                                        <input type="text" class="form-control" name="price">                                    </div>                                </div>                                <div class="line line-dashed line-lg pull-in"></div>                                                                 <div class="form-group">                                   <label class="col-sm-2 control-label">商品库存:</label>                                   <div class="col-sm-8">                                       <input type="number" class="form-control" name="stock">                                   </div>                                </div>                                 <div class="line line-dashed line-lg pull-in"></div>                                                                <div class="form-group">                                   <label class="col-sm-2 control-label">运费:</label>                                   <div class="col-sm-8">                                       <input type="text" class="form-control" name="luggage">                                   </div>                                </div>                                 <div class="line line-dashed line-lg pull-in"></div>                                                                 <div class="form-group">                                    <label class="col-sm-2 control-label">首页图片:</label>                                    <div class="col-sm-3"><input type="file" name="image1" class="filestyle"data-icon="false" id="f1" data-classButton="btn btn-default"data-classInput="form-control inline input-s"onchange="changeImg1()"  /> <input id="number" name="number" value='' style="display: none" /><input id="flag" name="flag" value='' style="display: none" />    <input id="imgNumber1" name="imgNumber1" value='' style="display: none" /></div><div class="col-sm-8"><label class="col-sm-2 control-label" style="margin-top:20px;">预览</label><div class="row aaaa1" style="position: relative; left: 0px;"></div><div style="height: 50px"></div></div>                                </div>                          <div style="margin-bottom: 100px;"></div>                                <div class="line line-dashed line-lg pull-in"></div>                                                                <div class="form-group" style="clear:both;"><label class="col-sm-2 control-label">上传banner商品图片:</label><div class="col-sm-3"><input type="file" name="image2" class="filestyle"data-icon="false" id="f2" data-classButton="btn btn-default"data-classInput="form-control inline input-s"onchange="changeImg2()" multiple="multiple" /> <input id="number2" name="number2" value='' style="display: none" />    <input id="imgNumber2" name="imgNumber2" value='' style="display: none" /></div><div class="col-sm-8"><label class="col-sm-2 control-label" style="margin-top:20px;">预览</label><div class="row aaaa2" style="position: relative; left: 0px;"></div><div style="height: 200px"></div></div></div><div style="margin-bottom: 100px;"></div>                                <div class="line line-dashed line-lg pull-in"></div>                                                                <div class="form-group">                                    <label class="col-sm-2 control-label">备注:</label>                                    <div class="col-sm-8" >                                       <textarea rows="7" style="width: 100%">                                        备注信息...                                       </textarea>                                    </div>                                </div>                                                                <div class="form-group">                                   <div class="col-sm-4 col-sm-offset-2">                                       <button type="reset" class="btn btn-default">取消</button>                                       <button type="submit" class="btn btn-primary">保存信息</button>                                   </div>                               </div>                            </form>
JS代码片段

<script type="text/javascript">function changeImg1() {$('.aaaa1').html('')var pic, file;pic = document.getElementById("preview1");file = document.getElementById("f1");var ext = file.value.substring(file.value.lastIndexOf(".") + 1).toLowerCase();// gif在IE浏览器暂时无法显示if (ext != 'png' && ext != 'jpg' && ext != 'jpeg') {alert("图片的格式必须为png或者jpg或者jpeg格式!");return;}var isIE = navigator.userAgent.match(/MSIE/) != null, isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null;if (isIE) {file.select();var reallocalpath = document.selection.createRange().text;// IE6浏览器设置img的src为本地路径可以直接显示图片if (isIE6) {pic.src = reallocalpath;} else {// 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\""+ reallocalpath + "\")";// 设置img的src为base64编码的透明图片 取消显示浏览器默认图片pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';}} else {html5Reader1(file);}}function html5Reader1(file) {var index = file.files.length$('#imgNumber1').val(index)for (var i = 0; i < file.files.length; i++) {var f = file.files[i];var reader = new FileReader();reader.readAsDataURL(f);reader.onload = function(e) {var teet = '<div> <img id="preview1" name="pic"style=" height: 100px; float: left; position: relative;margin: 1px 1px " src=' + this.result + '><div>'$('.aaaa1').append(teet)}}}function changeImg2() {$('.aaaa2').html('')var pic, file;pic = document.getElementById("preview2");file = document.getElementById("f2");var ext = file.value.substring(file.value.lastIndexOf(".") + 1).toLowerCase();// gif在IE浏览器暂时无法显示if (ext != 'png' && ext != 'jpg' && ext != 'jpeg') {alert("图片的格式必须为png或者jpg或者jpeg格式!");return;}var isIE = navigator.userAgent.match(/MSIE/) != null, isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null;if (isIE) {file.select();var reallocalpath = document.selection.createRange().text;// IE6浏览器设置img的src为本地路径可以直接显示图片if (isIE6) {pic.src = reallocalpath;} else {// 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\""+ reallocalpath + "\")";// 设置img的src为base64编码的透明图片 取消显示浏览器默认图片pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';}} else {html5Reader2(file);}}function html5Reader2(file) {var index = file.files.length$('#imgNumber2').val(index)for (var i = 0; i < file.files.length; i++) {var f = file.files[i];var reader = new FileReader();reader.readAsDataURL(f);reader.onload = function(e) {var teet = '<div> <img id="preview2" name="pic"style=" height: 100px; float: left; position: relative;margin: 1px 1px " src=' + this.result + '><div>'$('.aaaa2').append(teet)}}}</script>


java代码片段

@RequestMapping("/insertProduct.do")public ModelAndView insertProduct(HttpServletRequest request,ModelMap modelMap, @RequestParam MultipartFile image1,@RequestParam MultipartFile[] image2)throws Exception{String name = (String) request.getSession().getAttribute("loginName");if(StringUtils.isNotBlank(name)){System.out.println("--------------------上传商品后台-------------------------");        ProImageDO proImageDO = new ProImageDO();        String imagePath = null;        String imgNumber1 = getParameterCheck(request, "imgNumber1");// 接收首页图片数String imgNumber2 = getParameterCheck(request, "imgNumber2");// 接收banner图片数String productNo = codeGenerateComponent.nextCodeByType(PlatformCodeEnum.MARRY_PLATFORM);;   //通过随机数获取商品号    String cell = ConfigrationFactory.getConfigration().getPropertyValue("cell");//从配置文件中拿到手机号    String imageRelativePath1 = new String();if (null != imgNumber1) { //判断首页图片是否为空        if (null == image1.getContentType()|| image1.getContentType().split("/") == null) {imageRelativePath1 = String.valueOf(System.currentTimeMillis())+ ".jpg";//} else {if (image1.getContentType().split("/").length > 1) {imageRelativePath1 = String.valueOf(System.currentTimeMillis())+ "."+ image1.getContentType().split("/")[1];//} else {imageRelativePath1 = String.valueOf(System.currentTimeMillis()) + ".jpg";//}}imagePath = IMAGE_FILE + imageRelativePath1;//通过图片与图片路径将图片保存在指定位置ImageZipUtil.compressPic(image1, imagePath);imageRelativePath1 = IMAGE_PATH + imageRelativePath1;}try {String userId = userDAO.selectUserByCell(cell).getUserId();//用户IDString productName = request.getParameter("productName");   //商品名称String productType = request.getParameter("productType");   //商品大类String children = request.getParameter("children");      //商品小类Money  price = new Money(request.getParameter("price")); //现价Money  luggage = new Money(request.getParameter("luggage"));    //运费Money  oldPrice = new Money(request.getParameter("oldPrice"));  //原价double productOff = Double.valueOf(request.getParameter("price"))/Double.valueOf(request.getParameter("oldPrice"));  //商品折扣int    soleCount = 0;    //销售量String status = "0";     //商品状态int    stock = Integer.valueOf(request.getParameter("stock"));  //商品库存String productUrl = imageRelativePath1;        //商品图片String delFlg = "0";     //删除标识String creater = request.getParameter(" ");    //创建者String modifier = request.getParameter(" ");;  //更新者String memo = request.getParameter("memo");         //备注long count = productDAO.selectProductNO(productNo);if(count == 0 ){ProductDO productDO = new ProductDO();productDO.setUserId(userId);productDO.setProductNo(productNo);productDO.setProductName(productName);productDO.setProductType(productType);productDO.setChildren(children);productDO.setProductOff(productOff);productDO.setPrice(price);productDO.setLuggage(luggage);productDO.setOldPrice(oldPrice);productDO.setSoleCount(soleCount);productDO.setStatus(status);productDO.setStock(stock);productDO.setProductUrl(productUrl);productDO.setDelFlg(delFlg);productDO.setCreater(creater);productDO.setModifier(modifier);productDO.setMemo(memo);int count1 = productDAO.insertProduct(productDO);if(count1 <= 0)return new ModelAndView("mng/addProduct");}} catch (Exception e) {e.printStackTrace();}/** * 上传banner图片  */if (null != imgNumber1) { //判断首页图片是否为空if (null != imgNumber2) {  //判断banber图片是否为空int numb2 = Integer.parseInt(imgNumber2);String[] imageRelativePath2 = new String[numb2];String id = String.valueOf(System.currentTimeMillis());  //获取商品号for (int i = 0; i < image2.length; i++) {if (null == image2[i].getContentType()|| image2[i].getContentType().split("/") == null) {imageRelativePath2[i] = String.valueOf(System.currentTimeMillis()) + ".jpg";//} else {if (image2[i].getContentType().split("/").length > 1) {imageRelativePath2[i] = String.valueOf(System.currentTimeMillis())+ "."+ image2[i].getContentType().split("/")[1];//} else {imageRelativePath2[i] = String.valueOf(System.currentTimeMillis()) + ".jpg";//}}imagePath = IMAGE_FILE + imageRelativePath2[i]; //图片的存储地址ImageZipUtil.compressPic(image2[i], imagePath); //将图片保存在指定位置imageRelativePath2[i] = IMAGE_PATH + imageRelativePath2[i];  //图片的urlproImageDO.setProductNo(id);proImageDO.setImg(imageRelativePath2[i]);int count = proImageDAO.insert(proImageDO);if(count <= 0)return new ModelAndView("mng/addProduct");}}}return new ModelAndView("mng/addProductSuccess");}return new ModelAndView("mng/mngLogin");}/** * 判断参数是否为空 * @param request * @param key * @return */ private String getParameterCheck(HttpServletRequest request, String key) {String Value = request.getParameter(key);    if(null==Value||Value.equals("")){    Value=null;}    return Value;}

.properties文件

run_mode=DEVapp_name=jiumelogging_root=/home/logs/jiumesys_loggingLevel=DEBUGsys_loggingLevel_info=DEBUGsys_logging_encoding=UTF-8jiume_htdocs=E:/eclipse workplace/onway/jiume/htdocscore_protocol=httpcore_web_port=5008ace_service_url= http://xxx.xx.xx.xxx:8080jiume_post_upload_image= C:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps_update/jiume/WEB-INF/classes/htdocs/templates/img/jiume_post_image=http://localhost:8080/jiumemng/img/#settlecore_service_url= http://xxx.xx.xxx.xxx:8083#account_service_url=http://xxx.xx.xx.xxx:8083#gotone_service_url = http://xxx.xx.xxx.xxx:8082


0 0
原创粉丝点击