bootstrap fileinput 组件整合SpringMVC上传图片到本地磁盘

1.搭建好基础框架,本文用的是SSM(Spring+SpringMVC+Mybatis),这里的过程就不在本文中讲了,之前我做个一个demo(ssm整合+用户模块),可以参考这个搭建好。

2.下载bootstrap fileinput组件源码: 
https://github.com/kartik-v/bootstrap-fileinput/

搭建后的效果图

图1. 
这里写图片描述

图2. 
这里写图片描述

图3. 
这里写图片描述

图4. 
这里写图片描述

图5.

这里写图片描述

在需要编写的jsp页面引入组件

本工程的路径界面如下:

这里写图片描述

在jsp引入组件需要的js,css,如下代码:

<!-- jq -->
<script type="text/javascript"
    src="<%=basePath%>static/plugs/jquery-3.1.1.min.js"></script>

<!-- bootstrap -->
<link rel="stylesheet"
    href="<%=basePath%>static/plugs/bootstrap/css/bootstrap.min.css">
<script type="text/javascript"
    src="<%=basePath%>static/plugs/bootstrap/js/bootstrap.min.js"></script>
<link href="<%=basePath%>css/xlstyle.css" rel="stylesheet">

<!-- 图片上传即使预览插件 -->
<link rel="stylesheet"
    href="<%=basePath%>static/plugs/bootstrap-fileinput/css/fileinput.min.css">
<script type="text/javascript"
    src="<%=basePath%>static/plugs/bootstrap-fileinput/js/fileinput.min.js"></script>
    <!-- 这个是汉化-->
<script type="text/javascript"
    src="<%=basePath%>static/plugs/bootstrap-fileinput/js/locales/zh.js"></script>
  •  

引入组件,这里以我自己写的网站为例:

<form class="form-horizontal" role="form" method="post"
                    action="<%=basePath%>addArticle" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">菜谱名称</label>
                        <div class="col-sm-10">
                            <input type="text" name="describ" class="col-sm-10 form-control"
                                placeholder="菜谱名称">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">菜谱封面</label>
                        <div class="col-sm-10">
                            <input type="file" name="myfile" data-ref="url2"
                                class="col-sm-10 myfile" value="" /> <input type="hidden"
                                name="url2" value="">
                        </div>
                    </div>
  •  

还有需要配置组件的详细js,我这里是放在了标签结束的后面:

以上省略
.........
</body>
<script type="text/javascript">
    $(".myfile").fileinput({
        //上传的地址
        uploadUrl:"<%=basePath%>food/uploadFile",
        uploadAsync : true, //默认异步上传
        showUpload : false, //是否显示上传按钮,跟随文本框的那个
        showRemove : false, //显示移除按钮,跟随文本框的那个
        showCaption : true,//是否显示标题,就是那个文本框
        showPreview : true, //是否显示预览,不写默认为true
        dropZoneEnabled : false,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
        //minImageWidth: 50, //图片的最小宽度
        //minImageHeight: 50,//图片的最小高度
        //maxImageWidth: 1000,//图片的最大宽度
        //maxImageHeight: 1000,//图片的最大高度
        //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
        //minFileCount: 0,
        maxFileCount : 1, //表示允许同时上传的最大文件个数
        enctype : 'multipart/form-data',
        validateInitialCount : true,
        previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany : "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
        allowedFileTypes : [ 'image' ],//配置允许文件上传的类型
        allowedPreviewTypes : [ 'image' ],//配置所有的被预览文件类型
        allowedPreviewMimeTypes : [ 'jpg', 'png', 'gif' ],//控制被预览的所有mime类型
        language : 'zh'
    })
    //异步上传返回结果处理
    $('.myfile').on('fileerror', function(event, data, msg) {
        console.log("fileerror");
        console.log(data);
    });
    //异步上传返回结果处理
    $(".myfile").on("fileuploaded", function(event, data, previewId, index) {
        console.log("fileuploaded");
        var ref = $(this).attr("data-ref");
        $("input[name='" + ref + "']").val(data.response.url);

    });

    //同步上传错误处理
    $('.myfile').on('filebatchuploaderror', function(event, data, msg) {
        console.log("filebatchuploaderror");
        console.log(data);
    });

    //同步上传返回结果处理
    $(".myfile").on("filebatchuploadsuccess",
            function(event, data, previewId, index) {
                console.log("filebatchuploadsuccess");
                console.log(data);
            });

    //上传前
    $('.myfile').on('filepreupload', function(event, data, previewId, index) {
        console.log("filepreupload");
    });
</script>
  • 修改的方法
    
    function child(data) {
    		var imge =[];
    		var con =   []; 
    		selectPick();
    		$("#id").val(data.id);
    		$("#scenicImge").val(data.scenicImge);
    		$("#imageSize").val(data.imageSize);
    		$("#pictureName").val(data.pictureName);
    		$("#scenicId").val(data.scenicId);
    		$("#background").val(data.background);
    		$("#backgroundSize").val(data.backgroundSize);
    		$("#backgroundName").val(data.backgroundName);
    		
    		if(data.scenicImge!=""&& data.scenicImge!=null){
    			 imge.push(apiManager.apiServerStrategy+data.scenicImge)
    			 con.push({caption: data.pictureName, size: data.imageSize, width: "120px", url: apiManager.apiServerStrategy+"/strategyTable/deleteImge?id="+data.id, key: 1})
    		}
    		edit_image(imge,con);
    		console.log(data.senicTypeId);
    		if(data.senicTypeId!=null){
    			$("#selectpickers").val(data.senicTypeId);
    		}
    		/*var backgroundImge =[];
    		var backgroundCon =   []; 
    		console.log(data);
    		if(data.background!="" && data.background!=null){
    			console.log("=======");
    			 backgroundImge.push(apiManager.apiServerStrategy+data.background)
    			 backgroundCon.push({caption: data.backgroundName, size: data.backgroundSize, width: "120px", url: apiManager.apiServerStrategy+"/strategyTable/deleteBackground?id="+data.id, key: 1})
    		}
    		console.log(backgroundImge);
    		console.log(backgroundCon);
    		 edit_background(backgroundImge,backgroundCon);*/
    	  
    	}
    		function edit_image(imge,con){  
    	        $(".myfile").fileinput({
    	            //上传的地址
    	            uploadUrl: apiManager.apiServerStrategy +"/strategyTable/uploadFile",
    	            uploadAsync : true, //默认异步上传
    	            showUpload : false, //是否显示上传按钮,跟随文本框的那个
    	            showRemove : false, //显示移除按钮,跟随文本框的那个
    	            showCaption : true,//是否显示标题,就是那个文本框
    	            showPreview : true, //是否显示预览,不写默认为true
    	            dropZoneEnabled : true,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
    	            //minImageWidth: 50, //图片的最小宽度
    	            //minImageHeight: 50,//图片的最小高度
    	            //maxImageWidth: 1000,//图片的最大宽度
    	            //maxImageHeight: 1000,//图片的最大高度
    	            //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
    	            //minFileCount: 0,
    	            maxFileCount : 1, //表示允许同时上传的最大文件个数
    	            enctype : 'multipart/form-data',
    	            validateInitialCount : true,
    	            previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
    	            msgFilesTooMany : "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
    	            allowedFileTypes : [ 'image' ],//配置允许文件上传的类型
    	            allowedPreviewTypes : [ 'image' ],//配置所有的被预览文件类型
    	            allowedPreviewMimeTypes : [ 'jpg', 'png', 'gif' ],//控制被预览的所有mime类型
    	            language : 'zh',
    	            initialPreviewAsData: true,  
    	            initialPreviewFileType: 'image',  
    	            initialPreview:imge, //要显示的图片的路径  
    	            initialPreviewConfig:con
    	
    	        })
    	        
    	        //异步上传返回结果处理
    	        $('.myfile').on('fileerror', function(event, data, msg) {
    	            console.log("fileerror");
    	            console.log(data);
    	        });
    	        //异步上传返回结果处理
    	        $(".myfile").on("fileuploaded", function(event, data, previewId, index) {
    	            var ref = $(this).attr("data-ref");
    	            $("input[name='" + ref + "']").val(data.response.url);
    	            $("#imageSize").val(data.response.imageSize);
    	            $("#pictureName").val(data.response.pictureName);
    	
    	        });
    	        //同步上传错误处理
    	        $('.myfile').on('filebatchuploaderror', function(event, data, msg) {
    	            console.log("filebatchuploaderror");
    	            console.log(data);
    	        });
    	        //同步上传返回结果处理
    	        $(".myfile").on("filebatchuploadsuccess",
    	                function(event, data, previewId, index) {
    	                    console.log("filebatchuploadsuccess");
    	                    console.log(data);
    	         });
    	         //删除预处理(删除之前想要做什么事)
    	       /*  $('.myfile').on('filepredelete', function(event, key) {
    	        	
    	        }); */
    	         //删除后的处理(删除图片时想要做什么事)
    	         $('.myfile').on('filedeleted', function(event, key) {
    	            var ref = $(this).attr("data-ref");
    	            $("input[name='" + ref + "']").val("");
    	            $("#imageSize").val("");
    	            $("#pictureName").val("");
    	            layer.msg("删除成功 ");
    	            
    	        }); 
    	        $('.myfile').on('filepreremove', function(event, id, index) {       //只是你删除重新选择的图片才会触发,而删除原图片不会触发。
    	            console.log('id = ' + id + ', index = ' + index);
    	         });
    	
    	
    	        $('.myfile').on('filepredelete', function(event, key, jqXHR, data) {  //就是在删除原图片之前触发,而新选择的图片不会触发。能满足我们的要求。
    	           console.log('Key = ' + key);
    	        });
    	        //上传前
    	        $('.myfile').on('filepreupload', function(event, data, previewId, index) {
    	            console.log("filepreupload");
    	        });
    	} 

     

配置tomcat的虚拟路径

如题,本次图片上传是要上传到服务器上别的磁盘位置,比如我的电脑作为服务器来说,一般情况下用tomcat上传图片只能上传到项目的某文件夹中,所以这里我们需要配置tomcat来打开tomcat的虚拟路径,让tomcat可以映射到本地磁盘的路径上。操作如下图:

1.双击这里 
这里写图片描述

2.点击我画圈的地方 
这里写图片描述

3.配置tomcat的虚拟路径

path:也就是我们tomcat的虚拟访问路径,Documnet Base是我们实际本地磁盘需要被映射的路径。

这里写图片描述

SpringMVC的Controller层编写

@Controller
@RequestMapping("/food")
public class PictureController {

    // uploadFile
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile myfile)
            throws IllegalStateException, IOException {
        // 原始名称
        String oldFileName = myfile.getOriginalFilename(); // 获取上传文件的原名
//      System.out.println(oldFileName);
        // 存储图片的虚拟本地路径(这里需要配置tomcat的web模块路径,双击猫进行配置)
        String saveFilePath = "E://picture";
        // 上传图片
        if (myfile != null && oldFileName != null && oldFileName.length() > 0) {
            // 新的图片名称
            String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            // 新图片
            File newFile = new File(saveFilePath + "\\" + newFileName);
            // 将内存中的数据写入磁盘
            myfile.transferTo(newFile);
            // 将新图片名称返回到前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("success", "成功啦");
            map.put("url", newFileName);
            return map;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", "图片不合法");
            return map;
        }
    }
}
//

var pathName=window.document.location.pathname;
var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
var imge =[];
var con =   []; 
$(".myfile").fileinput({
        //上传的地址
        uploadUrl: apiManager.apiServerStrategy + "/strategyTable/uploadFile",
        uploadAsync : true, //默认异步上传
        showUpload : false, //是否显示上传按钮,跟随文本框的那个
        showRemove : false, //显示移除按钮,跟随文本框的那个
        showCaption : true,//是否显示标题,就是那个文本框
        showPreview : true, //是否显示预览,不写默认为true
        dropZoneEnabled : true,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
        //minImageWidth: 50, //图片的最小宽度
        //minImageHeight: 50,//图片的最小高度
        //maxImageWidth: 1000,//图片的最大宽度
        //maxImageHeight: 1000,//图片的最大高度
        //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
        //minFileCount: 0,
        maxFileCount : 5, //表示允许同时上传的最大文件个数
        enctype : 'multipart/form-data',
        validateInitialCount : true,
        previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany : "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
        allowedFileTypes : [ 'image' ],//配置允许文件上传的类型
        allowedPreviewTypes : [ 'image' ],//配置所有的被预览文件类型
        allowedPreviewMimeTypes : [ 'jpg', 'png', 'gif' ],//控制被预览的所有mime类型
        language : 'zh',
    })
    
    //异步上传返回结果处理
    $('.myfile').on('fileerror', function(event, data, msg) {
        console.log("fileerror");
        console.log(data);
    });
    //异步上传返回结果处理
    $(".myfile").on("fileuploaded", function(event, data, previewId, index) {
        var ref = $(this).attr("data-ref");
        console.log(data.response.url);
        $("input[name='" + ref + "']").val(data.response.url);
        $("#imageSize").val(data.response.imageSize);
        $("#pictureName").val(data.response.pictureName);
    });

    //同步上传错误处理
    $('.myfile').on('filebatchuploaderror', function(event, data, msg) {
        console.log("filebatchuploaderror");
        console.log(data);
    });
    //同步上传返回结果处理
    $(".myfile").on("filebatchuploadsuccess",
            function(event, data, previewId, index) {
                console.log("filebatchuploadsuccess");
                console.log(data);
     });
    //上传前
    $('.myfile').on('filepreupload', function(event, data, previewId, index) {
        console.log("filepreupload");
    });
//没上传之前的删除
    $('.myfile').on('filesuccessremove', function(event, id) {  
    	$("#backgroundImg").val();
    	console.log($("#backgroundImg").val());  	
     $.post(apiManager.apiServerStrategy + "/strategyContent/deleteImgeByUrl", {
			imge: $("#backgroundImg").val() //将需要删除的newsId作为参数传入
		}, function(data) {
		
		}) 	
	});
关流的后台


public static Map<String, Object> uploadFile(MultipartFile[] myfile,String uploadFolder) throws IOException{
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	String urlImge="";
	    	String oldName = "";
	    	String image = "";
	    	FileOutputStream out = null;
	    	InputStream in = null;
	    	for(int i=0;i<myfile.length;i++) {
    	    	String oldFileName = myfile[i].getOriginalFilename(); // 获取上传文件的原名
    	    	 if (oldFileName != null && oldFileName.length() > 0) {
    	    		 // 新的图片名称
    		         String newFileName = CommonUtil.getDateFormat() + oldFileName.substring(oldFileName.lastIndexOf(".")); 
    		                File file = new File(uploadFolder, newFileName);
    		                if (!file.exists()) {
    		                    file.createNewFile();
    		                }
    		                in = myfile[i].getInputStream();
    		               try {  
    		                    //这里就会异常,如果文件名不存在的话。  
    		                	 out = new FileOutputStream(file);  
    		                	 byte[] cache = new byte[2560];
    		                	 int length = 0;
    	    		             while ((length = in.read(cache)) != -1) {
    	    		                    out.write(cache, 0, length);
    	    		             }
    	    		             out.flush();
    	    		             if (out != null) {
    	    		            	 out.close();
    	    		             }
    	    		             if (in != null) {
    	    		            	 in.close();
    	    		             }
    		                } catch (IOException e) {  
    		                    //这个主要是把出现的异常给人看见,不然就算异常了,看不到就找不到问题所在。  
    		                	e.getMessage();
    		                } finally {  
	    		                    if (out != null) {  
		    		                   try {
		    		                	   out.close(); // 关闭流  
		    		                    } catch (IOException e) {  
		    		                        e.getMessage();  
		    		                    }  
	    		                    }  
	    		                    if (in != null) {
			    		              try {
			        		               in.close();
			    		                } catch (IOException e) {  
		    		                       e.getMessage();  
		    		                    }  
	    		                    }
    		                }  
    		         String imageSize = CommonUtil.pathSize(file.toString());
    		         int s =  file.toString().indexOf(":");
    		         String url = file.toString().substring(s+1);
    		         urlImge += url+",";
    		         oldName += imageSize+",";
    		         image += oldFileName +",";
    	    	 }
    	    }
	    	System.gc();//系统进行资源强制回收
	    	map.put("url", urlImge.substring(0,urlImge.length()-1));
	    	map.put("imageSize", oldName.substring(0,oldName.length()-1));
	    	map.put("pictureName", image.substring(0,image.length()-1));
	    	return map;
	}
删除的后台

 public static String getUrlImge(String url,String imge){
			 int ie = url.indexOf(":");
			 String se = url.substring(0,ie+1);
			 //拼接地址
			 String address = se + imge;
			 File file=new File(address);
			 if(file.exists() && file.isFile()) {
				 file.delete();
			 }
			 return imge;
		}  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值