zoukankan      html  css  js  c++  java
  • form表单图片上传

    1、前端页面

    <div class="tkDiv" id="addLOGO" style="display:none;z-index:12;800px;height:auto;margin-left:-400px;margin-top: -160px">
    			
    	  		<div class="tk1_header" style="800px;height:40px;line-height:40px;background: #263552 !important;color: #ffffff !important;margin-left:-10px;margin-top:-10px;">
    	  			<span style="font-size: 16px;margin-left:20px;color:#FFF" id="gn_title">添加主页图片</span>
    	  			<a id="close_modal" style="30px;height:20px;background-size:20px;float: right;">×</a>
    	  		</div>
    	  		
    	  		<div class="tk1" id="addZ" style="750px;height:200px;">
    	  		<div class="tk1_content" id="registerDiv" style="750px;">
    	  			<form id="imageForm" class="bs-docs-example form-horizontal" method="post" action="<%=path %>/webCenter.do" enctype="multipart/form-data">
    	  			<input type="hidden" name="method" value="saveConferencesImage">
    				<input type="hidden" id="imageId" name="imageId" value="-1">
    		  			<table style="750px">
    		  				<tr height="50px">
    		  					<td align="right" width="150px" >
    		  						图片名称
    		  					</td>
    		  					<td>
    		  						<input id="imageName" class="form-control" name="imageName" type="text" style="margin-left:40px;display:inline-block;height:34px;"/>
    		  					</td>
    		  				</tr>
    		  				<tr height="50px">
    		  					<td align="right" width="150px" >
    		  						上传图片
    		  					</td>
    		  					<td>
    		  						<input id="imageFile"  name="imageFile" type="file" style="margin-left:40px;display:inline-block;height:34px;"/>
    		  					</td>
    		  				</tr>		  				
    		  			</table>
    		  		</form>
    	  		</div>
    	  		<div style="border-top: 1px solid rgba(0, 0, 0, 0.1);text-align: center;">
    	  			<input id="saveBtn" type="button" class="button" value="添 加" style="border-radius:0;260px;height:40px;margin:auto 50px;margin:20px; background: #263552 !important;color: #ffffff !important;"/>
    	  		</div>
    	  	</div>
    

      2、js代码

    $(function(){
    		$("#saveBtn").click(function(){
    			var imageName = $("#imageName").val();
    			var imageFile = $("#imageFile").val();
    			if(imageName == '' || imageName.length == 0){
    				alert("请输入图片名称");
    				return;
    			}if(imageFile == '' || imageFile.length == 0){
    				alert("请选择要上传的图片");
    				return;
    			}
    			var formData = new FormData();
    	            formData.append("imagePath", $("#imageFile")[0].files[0]);
    			$.ajax({
    				url:"<%=path%>/webCenter.do?uploadConImage",
    				type:"post",
    				data:formData,
    				dataType:"json",
    				// 告诉jQuery不要去处理发送的数据
    	            processData: false,
    	            // 告诉jQuery不要去设置Content-Type请求头
    	            contentType: false,
    	            beforeSend: function () {
    	               console.log("正在进行,请稍候");
    	            },
    				success:function(data){
    					if(data.state == 0){
    						alert(data.msg)
    					}else{
    						$("#imageForm").submit();
    					}
    				}
    			})
    		})
    })
    

      3、后台数据处理

      ① 第一步验证图片大小

    //判断图片大小,不是这个大小的提示不能上传
    @RequestMapping(params = "uploadConImage",method = RequestMethod.POST)
    	public void uploadConImage(HttpServletRequest request,HttpServletResponse response){
    		try{
    			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
    			MultipartFile mFile = mRequest.getFile("imagePath");
    			InputStream is = mFile.getInputStream();//输入流
    			BufferedImage bufferedImg = ImageIO.read(is);
    			int width = bufferedImg.getWidth();//获取图片宽高
    			int height = bufferedImg.getHeight();
    			JSONObject json = new JSONObject();
    			
    			if(width != 500 && height != 300){
    				float bili = (float)(new Float(height)/new Float(width));
    				float   b   =   (float)(Math.round(bili*100))/100;
    				if(b != new Float(0.45)){
    					json.accumulate("state", 0);
    					json.accumulate("msg", "请上传分辨率为500*300的图片或者长宽比为0.6的图片(高除以宽为0.6)");
    				}else{
    					json.accumulate("state", 1);
    				}
    			}else{
    				json.accumulate("state", 1);
    			}
    			writeJson(response, json.toString());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    

      ② 在js里面用$("#imageForm").submit();提交form表单,上传图片。注意:用form表单上传图片时,在from表单上要添加  enctype="multipart/form-data"  属性。form表单看上面代码,下面是后台数据处理。

    @RequestMapping(params = "method=saveConferencesImage",method = RequestMethod.POST)
    	public void saveConferencesImage(int imageId,String imageName,HttpServletRequest request,HttpServletResponse response){
    		try {
    			HttpSession session  = this.getSession(request);
    			Adminuser adminUser = session.getAttribute("centerAdminUser") == null?null:(Adminuser) session.getAttribute("centerAdminUser");
    			if(adminUser == null){
    				try {
    					response.sendRedirect(request.getContextPath()+"/center/index.jsp");
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}else{
    				String conId = request.getSession().getAttribute("conId") == null ? null: request.getSession().getAttribute("conId").toString();
    				if (conId == null) {
    					response.sendRedirect(request.getContextPath()+"/center/index.jsp");
    				}
    				Conferences conferences = webService.getConferencesById(Integer.parseInt(conId));
    				ConferencesImage conferencesImage = null;
    				if(imageId == -1){
    					conferencesImage = new ConferencesImage();
    				}else{
    					conferencesImage = webService.getConferencesImageById(imageId);
    				}
    				conferencesImage.setConferencesId(Integer.parseInt(conId));
    				conferencesImage.setImageName(imageName);
    				int level = webService.getConferencesImageLevel(Integer.parseInt(conId));
    				conferencesImage.setLevel(level);
    				MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;
    				MultipartFile mFile = mRequest.getFile("imageFile");
    				String fileName= mFile.getOriginalFilename();//获取文件名
    				fileName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
    				String newFileName = String.valueOf(System.currentTimeMillis())+"_mainPage"+fileName;
    				String filePath = request.getSession().getServletContext().getRealPath("/");
    				filePath = filePath + conferences.getAbbreviation()+"/images/mainPage/";
    				File file = new File(filePath);
    				if(!file.exists()){
    					file.mkdirs();
    				}
    				File saveFile = new File(filePath+newFileName);
    				mFile.transferTo(saveFile);
    				conferencesImage.setImageUrl("/"+conferences.getAbbreviation()+"/images/mainPage/"+newFileName);
    				webService.saveObject(conferencesImage);
    				response.sendRedirect(request.getContextPath()+"/webCenter.do?getConferencesImage");
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    

      

  • 相关阅读:
    2016.6.21 -Dmaven.multiModuleProjectDirectory system propery is not set,Check $M2_HOME environment variable and mvn script match.
    2016.6.21 maven:Failure to transfer ... from ....
    2016.7.5 如何在maven中添加所需依赖(只知道jar包的部分名字的情况)
    2016.6.20 maven更改repository的位置
    2016.6.20 maven下载与安装步骤
    2016.6.20 在Eclipse配置Tomcat服务器的步骤
    2016.6.21 eclipse配置server locations时按钮为灰色
    2016.6.21 将Eclipse中项目部署到tomcat下
    2016.6.20 tomcat安装出现No Java Virtual Machine found in..
    vue小荔枝,时间控件,动态按月份增减。
  • 原文地址:https://www.cnblogs.com/jichuang/p/10030560.html
Copyright © 2011-2022 走看看