效果图展示:
使用环境:
文件上传插件:bootstrap-fileinput,文档地址 http://plugins.krajee.com/file-input#pre-requisites
前段ui框架:bootstrap3
java后端框架:spring + mybatis
准备工作:
下载bootstrap-fileinput资源包放到项目中:http://pan.baidu.com/s/1hsvw3FQ 密码:c8wh
说明:如果前段ui框架不是bootstrap直接从第二步开始看
1.首先说一下bootstrap的模态框:
一般的打开模态框要在页面上隐藏一段html代码然后用$("#Id").modal('show')显示模态框或者$("#Id").modal('hide')隐藏模态框,本人觉得有点麻烦,没有easyui这样的直接用js代码打开方便 ,所以我对这个模态框进行了封装。来实现直接用js打开的效果。原理很简单就是应以自定义一个jquery的方法,传递一些设置的参数,然后js动态生成html代码然后将代码追加到页面的body后面,然后在调用$("#Id").modal('show')方法来打开模态框。模态框里面的内容是动态的 所以就需要一个url地址加载页面的内容。下面来看js代码
bootstrap-utils.js
jQuery.extend({
//模态弹出框
openModel:function(options){
var defaults={//设置默认参数
title:'',//模态框的标题
width:'100%',//模态框的默认宽度
height:$(window).height()-130+"px",//模态框的默认高度,默认取浏览器的可视高度
showOkButton:true,//是否显示确定按钮
id:"model_js",//模态框id
frameId:"modal_iframe",//iframeId
okButtonContent:"确定",//确定按钮显示的内容
cancelButtonContent:"关闭"//取消按钮显示的内容
}
var opts = $.extend(defaults,options);
var str = "";
str+="<div class='modal fade' id='"+opts.id+"' tabindex='-1' role='basic' aria-hidden='true'>";
str+=" <div class='modal-dialog'>";
str+=" <div class='modal-content'>";
if(opts.title != ""){
str+=" <div class='modal-header' style='height:30px;'>";
str+=" <button type='button' class='close' data-dismiss='modal' aria-hidden='true' style='margin-top:-10px;'>x</button>";
str+=" <h3 class='modal-title' style='margin-top:-10px;'><b>"+opts.title+"</b></h3>";
str+=" </div>";
}
str+=" <div class='modal-body' style='padding:0px;'>";
str+=" </div>";
str+=" <div class='modal-footer' style='height:35px;padding:0px;'>";
if(opts.showOkButton){
str+=" <button type='button' class='btn btn-primary btn-sm' οnclick='"+opts.ok+"();'>"+opts.okButtonContent+"</button>";
}
str+=" <button type='button' class='btn btn-default btn-sm' data-dismiss='modal'>"+opts.cancelButtonContent+"</button>";
str+=" </div>";
str+=" </div>";
str+=" </div>";
str+="</div>";
//如果当前页面不选在当前id的模态框才追加模态框html
if($("body").find("#"+opts.id+"").length == 0){
$("body").append(str);
}else{
$("body").find("#"+opts.id+"").remove();
$("body").append(str);
}
//如果参数传递的宽度或者高度不是px格式的则加上px
var height = (opts.height+"").indexOf("px") >= 0 ? opts.height : opts.height+"px";
var width = (opts.width+"").indexOf("px") >= 0 || (opts.width+"").indexOf("%") >= 0 ? opts.width : opts.width+"px";
//设置页面iframe的地址
$("#"+opts.id+"").find(".modal-body").html("<iframe name='"+opts.frameId+"' style='width:99%;height:"+height+";border:0px;' scrolling='yes' src='"+opts.url+"'></iframe>");
$("#"+opts.id+"").find(".modal-dialog").css({"width":width,"height":height});
//显示模态框
$("#"+opts.id+"").modal("show");
}
});
下面来看调用方式:
$.openModel({
url:'editPhoto.jsp',
frameId:'roomIframe',
id:'roomModel',
width:900,
ok:'getCropData'//点击确定按钮执行的函数
});
2.非bootstrap框架使用
说明:不是用bootstrap框架为了避免样式冲突,我这里用iframe方式,直接访问photoUploadInit.jsp
调用方式:<a href="photoUploadInit.jsp">选择图片<.a>
上传初始化页面:photoUploadInit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//这里获取一些业务需要的参数,请自行根据业务进行修改
String serviceId = request.getParameter("serviceId");//业务id
String resourceType = request.getParameter("resourceType");//业务类型,101,头像,2.图片
%>
<iframe src="<%=path %>/pages/plugins/photoManage/photoUpload.jsp?serviceId=<%=serviceId %>" style="width:99%;height:100%;border:0px;overflow:hidden;"></iframe>
3.bootstrap框架调用
调用方式:
<input id="roomPhotoEdit" type="button" value="房间照片编辑"/>
$("#roomPhotoEdit").click(function(){
$.openModel({
url:'photoUpload.jsp',
frameId:'myFrame',
showOkButton:false,
id:'myModel',
width:900,
ok:'getCropData'//点击确定按钮执行的函数
});
});
4.图片上传页面:photoUpload.jsp
<%@page import="com.laiqu.backend.common.util.StringUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String serviceId = request.getParameter("serviceId");
String resourceType = request.getParameter("resourceType");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--资源路径根据自己的项目结构进行修改-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<link href="<%=path %>/pages/plugins/photoManage/bootstrap-fileinput/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="<%=path %>/pages/plugins/photoManage/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="<%=path %>/pages/plugins/photoManage/bootstrap-fileinput/js/fileinput.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" type="text/javascript"></script>
<script src="<%=path %>/pages/plugins/photoManage/bootstrap-fileinput/js/fileinput_locale_zh.js" type="text/javascript"></script>
<script type="text/javascript">
//获取sessionId
function getSessionId(){
var c_name = 'JSESSIONID';
if(document.cookie.length>0){
c_start=document.cookie.indexOf(c_name + "=")
if(c_start!=-1){
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if(c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end));
}
}
}
$(document).ready(function() {
initData();//初始化
$("#file-upload").fileinput({
language: 'zh',
uploadUrl: '<%=path%>/fileInput/photoManage.do?opType=2&sessionId="+getSessionId()+"',
allowedFileExtensions : ['jpg', 'png','gif'],
showUpload: false,
showCaption: false,
browseClass: "btn btn-primary",
maxFileSize: 2048,
extra:{id:getSessionId()},
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
});
//文件上传成功
$('#file-upload').on('fileuploaded', function(event, file, previewId, index, reader) {
setTimeout(function(){
initData();
},1000);
});
//导入文件上传完成之后的事件
$('#file-upload').on('filebatchuploadsuccess', function(event, files, extra) {
setTimeout(function(){
initData();
},1000);
});
//文件删除之后
$('#file-upload').on('filedeleted', function(event, key) {
});
});
//根据业务id,业务类型查询上传的图片,并且将图片显示到编辑器中
function initData(){
var str1 = "[",str2 = "[";
$.ajax({
type:"post",
async:false,
url:"<%=path%>/fileInput/photoManage.do",
data:{keyPrimary:<%=serviceId%>,opType:1,rType:<%=resourceType%>},
dataType:"json",
success:function(data){
for(var i = 0;i < data.photoInfo.length;i++){
var ss = "";
//如果是封面的,显示文字标示
if(data.photoInfo[i].defaultMiddle == "1"){
ss = "<div style='background-color:white;position:absolute;width:50px;height:20px;color:red;font-weight:bold;padding:0;margin:0;line-height:15px;'>封面</div>";
}
str1+="\"";
str1+=""+ss+"<img src='"+data.photoInfo[i].resourcePath+"' class='file-preview-image' title='"+data.photoInfo[i].resourceName+"' alt='"+data.photoInfo[i].resourceName+"' style='width:auto;height:160px;'>";
str1+="\",";
str2+="{";
str2+=" caption: '"+data.photoInfo[i].resourceOriginal+"',";
str2+=" width: '120px', ";
str2+=" url: '<%=path%>/fileInput/photoManage.do?opType=3&resourceId="+data.photoInfo[i].resourceId+"',";
str2+=" key: "+data.photoInfo[i].resourceId+", ";
str2+=" extra: {id: "+data.photoInfo[i].resourceId+"}";
str2+="},";
}
str1 += "]",str2 += "]";
$("#file-upload").fileinput('refresh',{
initialPreview:eval(str1)
,initialPreviewConfig: eval(str2)
,layoutTemplates :{
footer: '<div class="file-thumbnail-footer">\n' +
' <div class="file-caption-name" style="width:{width}">{caption}</div>\n' +
' {actions}\n' +
'</div>',
actions: '<div class="file-actions">\n' +
' <div class="file-footer-buttons">\n' +
' <a href="javascript:void();" class=\'cover_a\' style="font-size:11px;">设为封面</a> {upload}{delete}' +
' </div>\n' +
' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
' <div class="clearfix"></div>\n' +
'</div>',
}
});
}
});
}
$(function(){
$(".cover_a").live("click",function(){
var resourceId = $(this).next().attr("data-key");
$.ajax({
type:'post',
url:'<%=path%>/fileInput/photoManage.do',
data:{opType:4,resourceId:resourceId},
dataType:'json',
success:function(data){
if(data.status == "true"){
initData();
}else{
alert("系统错误");
}
},
error:function(){
alert("操作失败");
}
});
});
})
</script>
</head>
<body style="padding:0px;margin:0px;">
<form enctype="multipart/form-data">
<input id="file-upload" class="file" type="file" multiple data-preview-file-type="any" data-upload-url="<%=path%>/fileInput/photoManage.do?opType=2&keyPrimary=<%=serviceId%>&rType=<%=resourceType%>" data-preview-file-icon="">
</form>
</body>
</html>
5.后台上传代码 PhotoManange.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
/**
* 文件上传工具类
* @author 93908
*
*/
@Controller
@RequestMapping("fileInput")
public class PhotoManange {
@Autowired
JdbcTemplate baseDao;
@RequestMapping("/photoManage")
@ResponseBody
public String photoManage(HttpServletRequest request,HttpServletResponse response){
Map params=ParamUtil.toMap(request);
HashMap<String,Object> resultMap = new HashMap<String,Object>();
PrintWriter out = null;
if("1".equals(String.valueOf(params.get("opType")))){//根据业务id查询上传的图片
try {
out = response.getWriter();
String rType = String.valueOf(params.get("rType"));
List<Map<String, Object>> resultList;
/*
这里处理根据业务id查询图片列表
*/
resultMap.put("photoInfo", resultList);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
resultMap.put("status", "false");
resultMap.put("message", "系统错误");
}finally{
out.print(JSONObject.fromObject(resultMap));
}
}else if("2".equals(String.valueOf(params.get("opType")))){//上传图片
try {
out = response.getWriter();
//上传照片
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
String fileOldName = file.getOriginalFilename();
if(fileOldName.trim() !=""){
try {
String suffix = fileOldName.substring(fileOldName.lastIndexOf("."));//文件后缀名称
/*
这里处理图片上传并且保存到数据库,请参考我的博客http://blog.youkuaiyun.com/ntotl/article/details/51479953
*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
//记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
System.out.println(finaltime - pre);
}
}
resultMap.put("id", StringUtils.isNotBlank(params.get("sessionId")+"") ? String.valueOf(params.get("sessionId")) : "");
out.print(JSONObject.fromObject(resultMap));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else if("3".equals(String.valueOf(params.get("opType")))){//删除图片
try {
out = response.getWriter();
int resourceId = StringUtils.isNotBlank(params.get("resourceId")+"") ? Integer.parseInt(String.valueOf(params.get("resourceId"))) : 0;
/*
这里处理删除的操作
*/
resultMap.put("id", resourceId);
out.print(JSONObject.fromObject(resultMap));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if("4".equals(String.valueOf(params.get("opType")))){//设为封面
try {
out = response.getWriter();
int resourceId = StringUtils.isNotBlank(params.get("resourceId")+"") ? Integer.parseInt(String.valueOf(params.get("resourceId"))) : 0;
/*
这里处理上传封面的操作
*/
resultMap.put("status", "true");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resultMap.put("status", "false");
}
out.print(JSONObject.fromObject(resultMap));
}
return null;
}
}
用到的工具类:StringUtils.java
功能:字符串判空方法,在org.apache.commons.lang.StringUtils在基础上增加了“null”的判断
public class StringUtils {
public static boolean isNotBlank(String str){
if(
str == null
|| org.apache.commons.lang.StringUtils.isBlank(str)
|| "null".equals(str)
){
return false;
}
return true;
}
public static boolean isBlank(String str){
if(
str == null
|| org.apache.commons.lang.StringUtils.isBlank(str)
|| "null".equals(str)
){
return true;
}
return false;
}
}
参数处理函数:ParamUtil.java
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ParamUtil {
/**
* 从request中获得参数Map,并返回可读的Map
*
* @param request
* @return
*/
@SuppressWarnings("unchecked")
public static Map toMap(HttpServletRequest request) {
// 返回值Map
Map returnMap = new HashMap();
try {
request.setCharacterEncoding("UTF-8");
// 参数Map
Map properties = request.getParameterMap();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
returnMap.put(name, value);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnMap;
}
//获取map对象指定key的值,可以设置默认值
public static String nullDeal(Map params, String key, String defaultValue){
if(params == null || !StringUtil.isNorBlank(params.get(key)+"")){
return defaultValue;
}
return String.valueOf(params.get(key));
}
}