上传图片的代码demo

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"
											οnchange="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"
											οnchange="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();//用户ID	
				String 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];  //图片的url
						
						proImageDO.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=DEV
app_name=jiume

logging_root=/home/logs/jiume
sys_loggingLevel=DEBUG
sys_loggingLevel_info=DEBUG
sys_logging_encoding=UTF-8


jiume_htdocs=E:/eclipse workplace/onway/jiume/htdocs

core_protocol=http
core_web_port=5008

ace_service_url= http://xxx.xx.xx.xxx:8080

jiume_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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值