springboot + maven 图片上传(完整版)

1、前端显示


2、数据库显示


3、代码:

3.1、前端代码

<div class="sub-input">
					<form id="form-sub" method="post">
						<p>
							<a href="#" id='' style='width: 100%;'>
								<img src="${re.contextPath}/plugin/index/images/addphoto.png" style='margin:0 auto;display: block;margin-top: 10px' οnclick='fileSelect()' id='fileimg'
								 width="110" height="120">
							</a>
							<input type="file" style="display: none" id="choseImg" οnchange="fileChange()" name="file">
							<input type="hidden" id="impfilepath" name="impfilepath">
						</p>
						<p>
							<input type="text" name="username" id="username" placeholder='姓名' />
						</p>
						<p>
							<input type="text" name="idcard" id="idcard" placeholder='身份证号' />
						</p>
						<p>
							<input type="text" name="casetype" id="casetype" placeholder='案由' />
						</p>
						<!-- 	<p class='dateinput'>
							<input type="text" placeholder=" 开始时间 " readonly="readonly" id="begintime" name="begintime" class="Wdate" οnfοcus="WdatePicker({skin:'twoer',isShowClear:false,dateFmt:'yyyy-MM-dd',startDate:'%y-%M-%d',maxDate:'#F{$dp.$D(\'endtime\')||\'%y-%M-%d\'}'})" />
					
											<input type="text" placeholder=" 结束时间 " readonly="readonly" id="endtime" name="endtime"   class="Wdate" οnfοcus="WdatePicker({skin:'twoer',isShowClear:false,dateFmt:'yyyy-MM-dd',minDate:'#F{$dp.$D(\'begintime\')}',maxDate:'%y-%M-%d',startDate:'%y-%M-%d'})" />
					</p> -->

					</form>
					<div class="" style='width: 60%;margin: 0 auto;'>
						<p class='searchBox fl'>
							<button id='trailer-search'>搜索</button>
						</p>
						<p class='searchBox fl' style="margin-left: 6px">
							<button id='sub-btn'>提交</button>
						</p>
					</div>

				</div>
//上传图片
	function fileSelect() {
		$('#choseImg').click();
	}
	//文件选择后触发函数
	function fileChange() {
		/*window.URL.createObjectURL本地预览*/
		var fileImg = window.URL.createObjectURL($("#choseImg")[0].files[0]);
		$("#fileimg").attr('src', fileImg);
		// $("#avatar").val(fileImg);
		$("#fileimg").load(function () {
			window.URL.revokeObjectURL(fileImg);
		})  /*当图片加载后释放内存空间,但在jQuery3.2.1中会报错。浏览器关闭后也会自动释放*/
	}
$("#sub-btn").click(function () {

		//const _param = {name:$('#username').val(),idcard:$('#idcard').val()}
		submitWaring()
	});
		//信息提交验证
    function submitWaring(from){
                var name =$('#username').val();
                var  identity=$('#idcard').val();
                var reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)/;
                    if(name.length==0){
                        layer.alert('姓名不能为空!!!');
                        return false;
                    }
                    
                        if(identity.length!=0){
                            if(!(reg).test(identity)){
                                layer.alert("身份证输入不合法");		
                                return  false;
                            }
                        }
                
                addWarning();		
            }		
function addWarning(){
    layer.confirm('是否确认提交', {
            btn: ['确认', '取消']
            }, function (index) {
                $.ajax({
                        url: "addWarning",
                        type: "post",
                        data: {name:$('#username').val(),identity:$('#idcard').val(),casetype: $('#casetype').val(),impfilepath: $('#impfilepath').val()},
                        dataType: "json",
                        success: function (d) {
                                alert("提交成功!");
                                layer.close(index);
                                $('#form-sub')[0].reset();  
                                $("#fileimg").attr('src', '${re.contextPath}/plugin/index/images/addphoto.png');
                        }
                        })  
            }, function () {
            return;
            });		      
}

fileinput代码:

var $=jQuery.noConflict();
 $("#choseImg").fileinput({
    	language: 'zh', //设置语言
        uploadUrl: 'uploadimg', 
        showUpload: false, //是否显示上传按钮  
        showRemove:false,  
        showPreview: false,//是否预览
        dropZoneEnabled: false,  
        resizeImage: false,
        showCaption: false,//是否显示标题  
        // allowedPreviewTypes: ['image'],  
       allowedFileTypes: ['xls', 'xlsx','tpces','txt','zip'],  
       allowedFileExtensions:  ['xls', 'xlsx','tpces','txt','zip'], 
           maxFileSize : 20000000000,  
           maxFileCount: 1,  
           previewFileIcon: "",
           enctype: 'multipart/form-data',
           uploadAsync: true, //同步上传 
    		}).on("filebatchselected", function(event, files) {
    		    $(this).fileinput("upload");
    		}).on("fileuploaded", function(event, data) {			
    	
    	     }
    	  );
   $("#choseImg").on("filebatchuploadsuccess", function (event, data, previewId, index) {
    	 if(data.response){ 
    	
    		 var impfilepath = data.response.filePath;
    		// alert(impfilepath);
    		  if(impfilepath!=null){
    			
    			  $('#impfilepath').val(impfilepath);
    		  }
     	  }
    }); 

需要用到的js:

<script src="${re.contextPath}/plugin/fileinput/js/fileinput.min.js" type="text/javascript"></script>
<script src="${re.contextPath}/plugin/fileinput/js/fileinput_locale_zh.js" type="text/javascript"></script>
<script src="${re.contextPath}/plugin/ajaxform/ajaxForm.js" type="text/javascript"></script>
<script  type="text/javascript" src="${re.contextPath }/plugin/bootstrap-duallistbox/js/jquery.bootstrap-duallistbox.js"></script>
<script  type="text/javascript" src="${re.contextPath }/plugin/bootstrap-duallistbox/js/jquery.bootstrap-duallistbox.min.js"></script>
   <style type="text/css">
  .btn-primary {
    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;
    display: none;
}
.progress {
    height: 20px;
    margin-bottom: 20px;
    overflow: hidden;
    background-color: #f5f5f5;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
    display: none;
}
.btn-default {
    color: #333;
    background-color: #fff;
    border-color: #ccc;
    display: none;
}
  </style>

3.2、java代码:

private  String uploadPath = "c:\\export\\";
需要定义一个已知路径,因为浏览器无法获取本地图片路径,我们将图片复制到已知路径下,再返回图片路径
 /**
     * @author
     * @param request
     * @param response
     * @return 上传图片
     * @throws Exception
     */
     @ResponseBody
 	 @RequestMapping(value = "uploadimg",method = RequestMethod.POST)
 	public Map<String, Object>   uploadimg(HttpServletRequest request,HttpServletResponse response)
       throws Exception {
		   request.setCharacterEncoding("UTF-8");
		
		   Map<String, Object> json = new HashMap<String, Object>();
		   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		   
		   /** 页面控件的文件流* */
		   MultipartFile multipartFile = null;
		   Map map =multipartRequest.getFileMap();
		    for (Iterator i = map.keySet().iterator(); i.hasNext();) {
		           Object obj = i.next();
		           multipartFile=(MultipartFile) map.get(obj);
		
		          }
		   /** 获取文件的后缀* */
		   String filename = multipartFile.getOriginalFilename();
		   File file = new File(uploadPath);        
		   if (!file.exists()) {        
		   file.mkdirs();        
		   }   
		   Map<String ,Object> sysParamMap = new HashMap<String,Object>();
		   String filePath = uploadPath + filename;
		   sysParamMap.put("filePath", filePath);
		   File uploadFile = new File(filePath);
		   FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);   
		   return sysParamMap;
 	  }

数据入库:

 @ResponseBody   
   @RequestMapping(value = "addWarning",method = RequestMethod.POST)
 		public Object addWarning(){
 		Map<String, Object> map = getMapParams();
 		JSONObject obj=new JSONObject();
 		//得到图片路径
 	    String impfilepath= map.get("impfilepath").toString();
 	    File file = new File(impfilepath);
 	    byte[] data = getBytes(file);
 	     try {
 			if(map!=null){
 				Warning warn = new Warning();
 				warn.setNAME(map.get("name").toString());
 				warn.setIDENTITY(map.get("identity").toString());
 				warn.setCASETYPE(map.get("casetype").toString());
 				warn.setPIC(data);
 				warn.setUSER_ID(this.getUser().getUsername().toString());
 				warningMapper.addWarning(warn);
 				rundeletefile(impfilepath);
 				obj.put("info", "提交成功");
 				}else{
 					obj.put("info", "提交失败");
 				}
 		} catch (MyException e) {
           e.printStackTrace();		}
 	     	
 		   	Object jsonObject = JSONObject.toJSON(obj);
 	        return jsonObject;
 	 }

文件转byte[]:

/**
 * 文件转byte[]
 * @param file
 * @return
 */
   public byte[] getBytes(File file){  
       
       byte[] buffer = null;
       if (file == null){
           return buffer;
       } else {             
           try {     
               FileInputStream fis = new FileInputStream(file);  
               ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
               byte[] b = new byte[1000];  
               int n;  
               while ((n = fis.read(b)) != -1) {  
                   bos.write(b, 0, n);  
               }  
               fis.close();  
               bos.close();  
               buffer = bos.toByteArray();  
           } catch (FileNotFoundException e) {  
               e.printStackTrace();  
           } catch (IOException e) {  
               e.printStackTrace();  
           }
           
       }
         
        return buffer;  
 }

删除临时文件:

/** 
    * 删除临时文件 
    */ 
    private void rundeletefile(String delpath) { 
           try { 

                   File file = new File(delpath); 
                   if (!file.isDirectory()) { 
                           file.delete(); 
                   }
                   } 

           } catch (Exception e) { 
                   System.out.println("rundeletefile()   Exception:" + e.getMessage()); 
           } 
   }



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟进军大神陆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值