bootstrap多檔案預覽上傳
效果圖展示:
使用環境:
檔案上傳外掛: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' onclick='"+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("."));//檔案字尾名稱
/*
*/
} 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));
}
}