图片上传和批量上传已经预览效果,前后端超级详细

图片上传和批量上传已经预览效果,前后端超级详细_第1张图片图片上传和批量上传已经预览效果,前后端超级详细_第2张图片










<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>title>
 <link rel="stylesheet" href="../libs/layui/css/layui.css"  media="all">
 <script src="../js/jquery.min.js">script> 
	<script type="text/javascript" src="../js/jquery.cookie.js">script>

	<script src="../libs/layui/layui.all.js">script>
	<script src="../js/bootstrap.min.js">script>
	<script type="text/javascript" src="../js/xadmin.js">script>
	<script type="text/javascript" src="../js/global.js">script>
	<script type="text/javascript" src="../js/jquery.ext.js">script>
	<script src="../js/base.js">script>
	<script src="../js/custom.min.js">script>
	<script src="../libs/layui/lay/modules/laydate.js">script>
<style>
 .tablePage{
    padding:20px 20px
   }
  .table{
    text-align:center
    
   }
  .search{
    text-align:left;
   }
   .input{
     width:30%;
     float:left
   }
  .button{
   padding:10px 20px;
   }
   .search{
     margin-left:20px
   }
 
 style>
 <style type="text/css"> 
.layui-table-cell{
	height:auto!important;
	white-space:normal;
}
 
style> 
head>
<body>
     <div  class="tablePage">
 <div class="search">
  <div   id="oprationBtn"> 
      <input type="text" name="photoAlbumName" id="photoAlbumName"  style="visibility: hidden;" lay-verify="title" autocomplete="off" placeholder="请输入相册名称" class="layui-input input" >
      	<button type="button" class="layui-btn button"  style="visibility: hidden;" onclick="submitBtn()">搜索button>
        <button type="button" style="float:right" class="layui-btn button"  onclick="addPhoto()">上传照片button>
     div>
     div>
   <div class="table"> 
<table class="layui-hide" id="baomingTable" lay-filter="baomingTable" >table>
 div>
 div>
 <script src="../js/layui.all.js">script>
<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" href="{{d.photo_url}}" download="{{d.fileName}}.jpg" >下载</a>
  <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
script>
<script type="text/html" id="status">
     {{#  if(d.status == 1){ }}
        <span>待审核</span>
  {{#  } else if(d.status==2){ }}
           审核通过
  {{#  } else { }}
  审核拒绝
{{#  } }}
script>
<script type="text/html" id="sex">
  {{#  if(d.sex == 1){ }}
        <span></span>
  {{#  } else if(d.sex==0){ }}{{#  } else { }}{{#  } }}
script>
<script type="text/html"  id="img">
 <image src="{{d.photo_url}}">

script>
    <script>
  var classId;
  var   name='';
  var  photoAlbumName='';
  var  albumId='';
 $(function() {
     albumId=$.cookie('albumId');
    getData();
 })
 	function getData() {
     	   var  data={
     	        "albumId":albumId
              };
     	layui.use('table', function(){
       	table = layui.table;
       	table.render({
       	    elem: '#baomingTable',
       	    id : "jsSelect",
       	    method : "POST",
    		url : serverUrl.url + serverUrl.queryClassPhots,
    		where : data
    		,page: true 
		    ,limit:10
		    ,height:450
		    ,even: true
		    ,loading:true
       	      ,
       	    cols: [[ 
	       	{type:'numbers', title: '序号',align:'center', width: '25%'}
            ,{field: 'photo_url', align:'center',title: '相册图片',width:'25%',templet: function (d) {
	              return '
+d.photo_url+'" alt="" width="50px" height="50px" οnclick="showBigImage(this)">
'
; }} ,{field: 'create_date', align:'center',title:'创建时间',width: '25%'} ,{field: 'right', title:'操作', align:'center', templet: '#barDemo'} ]], limit : 10, page : true }); }); }; layui.use('table', function(){ var table = layui.table; //监听表格复选框选择 //监听工具条 table.on('tool(baomingTable)', function(obj){ var data = obj.data; $.cookie('photoAlbumName',data.resource_title); $.cookie('resourceUrl',data.resource_url); if(obj.event === 'downLoad'){ var data1={ "name":"ssssasd", "fileName":data.resource_url, } downLoad(data1); } else if(obj.event === 'refuse'){ }else if(obj.event==='look'){ $.cookie('guideOptionType','1'); details('查看'); }else if(obj.event==='edit'){ $.cookie('guideOptionType','2'); $.cookie('guideId',data.resource_id); details('编辑'); }else if(obj.event==='del'){ layer.confirm('确定删除吗?', function(index){ var data1={ "del":1, "photoId":data.photo_id } delGuide(data1); }); } }); }); //显示大图片 function showBigImage(e) { layer.open({ type: 1, title: false, closeBtn: 0, shadeClose: true, //点击阴影关闭 area: ['500px', '500px'], //宽高 content: "
+ $(e).attr('src') + " />
"
}); } function submitBtn(){ //搜索 photoAlbumName=$("#photoAlbumName").val(); getData(); } function addPhoto(){ upImg(); } function downLoad(params){ $.ajax({ type : "POST", dataType : "json", url : serverUrl.url + serverUrl.downloadFile, data : params, cache : false, success : function(result) { if (result.returnCode == 0) { var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); layer.msg('操作成功!',{icon:0}); $(".layui-laypage-btn").click(); layer.close(index); } else { layer.msg('' + result.reason + ''
, { icon : 2 }); } }, error: function() { layer.msg('' + '下载失败!' + ''
, { icon : 2 }); } }); } function delGuide(params){ $.ajax({ type : "POST", dataType : "json", url : serverUrl.url + serverUrl.saveOrUpdatePhoto, data : params, cache : false, success : function(result) { if (result.returnCode == 0) { var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); layer.msg('操作成功!',{icon:0}); $(".layui-laypage-btn").click(); layer.close(index); } else { layer.msg('' + result.reason + ''
, { icon : 2 }); } }, error: function() { layer.msg('' + '删除失败!' + ''
, { icon : 2 }); } }); } //上传图片的页面 function upImg(){ parent.layer.open({ type: 2, title: '上传班级图片', shadeClose: false, maxmin: false, fix: true, shade: [0.2, '#393D49'], area: ['730px', '380px'], scrollbar: false, content: 'photo_add1.html', end: function () { //$(".layui-laypage-btn").click(); getData(); } }); }
script> body> html>

批量上传的添加页面及效果

图片上传和批量上传已经预览效果,前后端超级详细_第3张图片


<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>xxXX西安分校title>
     <link href="../css/custom.min.css" rel="stylesheet">
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="../css/font.css">
<link rel="stylesheet" href="../css/xadmin.css">
<link rel="stylesheet" href="../css/inputTags.css">
<link rel="stylesheet" href="../css/layui.css">
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen"
	href="../css/zTreeStyle.css">
<link rel="stylesheet" href="../css/treeselect.css">
<link rel="stylesheet" href="../css/base.css">
head>

<body class="nav-md">
    <div class="body">
        <div class="main_container" style="background-color: #ffffff">
            
            <div class="right_col" role="main">
                <div class="clearfix">div>
                <div class="row">
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <div class="x_panel">
                            <div class="x_content" style="margin-left:20px">
                                <form class="form-horizontal form-label-left">

 
                                        <div class="layui-upload">
                                        <button type="button" class="layui-btn" id="test2" name="image[]">班级图片上传button> 
                                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;width: 630px;" >
                                                                                                                    预览图:
    									<div class="layui-upload-list" id="photoUrl" >div>
 										blockquote>
										div>
										


                                form>
                               
                            div>
                        div>
                    div>
                div>
                 <div class="form-group">
                                    <div class="col-md-12 col-xs-12" style="text-align: center">
                                            <button type="button"  onclick="cancleFunction()" class="btn btn-primary" style="margin-left: -5px;">取消button>
                                            <button type="submit" onclick="submitFunction()" class="btn btn-primary" style="margin-left: 41px;">确定button>
                                    div>
                                div>
            div>
        div>
    div>
    <style>
            .col-md-7{
                height: 28px;
                margin-top: 4px;
            }
        style>
      <script type="text/javascript" src="../libs/layui/layui.js"
	charset="utf-8">script>
<script type="text/javascript" src="../js/jquery-3.3.1.min.js">script>
<script type="text/javascript" src="../js/inputTags.js">script>

<script type="text/javascript" src="../js/global.js">script>
   <script type="text/javascript" src="../js/jquery.cookie.js">script>
 <script type="text/javascript">
 var photoAlbumId='';
 var  photoUrl='';
 var arr=[];
  $(function(){
  photoAlbumId=$.cookie('albumId');
 })
 
 layui.use('upload', function(){
  var $ = layui.jquery
  ,upload = layui.upload;
  
  //普通图片上传  '/upload/'
  var uploadInst = upload.render({
    elem: '#test1'
    ,url: serverUrl.url + serverUrl.upload
    ,before: function(obj){
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
        $('#photoUrl').attr('src', result); //图片链接(base64)
      });
    }
    ,done: function(res){
      //如果上传失败
      if(res.code > 0){
        return layer.msg('上传失败');
      }else{
       //图片上传成功
        $('#photoUrl').attr('src',  res.obj); //图片链接(base64)
       photoUrl=res.obj;
          return layer.msg('上传成功');
      }
       
    }
    ,error: function(){
      //演示失败状态,并实现重传
      var demoText = $('#demoText');
      demoText.html('上传失败 重试');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    }
  });
  
  
//多图片上传
  upload.render({
    elem: '#test2'
    ,url: serverUrl.url + serverUrl.uploadList //改成您自己的上传接口 οnclick="previewImg(this)"
    ,multiple: true
    ,before: function(obj){
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
    	  console.log('>>'+index);
    	  console.log('>>>>'+file);
    	  console.log('>>>>>>>>>'+result);
        $('#photoUrl').append('+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="height: 80px;width: 80px;" > ')
      });
    }
    ,done: function(res){
      //上传完毕
    	 if(res.code > 0){
    	        return layer.msg('上传失败');
    	      }else{
    	       //图片上传成功
    	        $('#photoUrl').attr('src',  res.obj); //图片链接(base64)
    	        photoUrl=res.obj;
    	      arr.push(res.obj);
    	     /*  var x=document.getElementById("photoUrl");
    	      
    	      x.innerHTML=arr; */
    	      
    	        console.log('array>>>>>>>'+arr);
    	          return layer.msg('上传成功');
    	      }
      
    },error: function(){
        //演示失败状态,并实现重传
        var demoText = $('#demoText');
        demoText.html('上传失败 重试');
        demoText.find('.demo-reload').on('click', function(){
          uploadInst.upload();
        });
      }
    
  });
  
 
  
  })
 
   

  
  function cancleFunction() {
			//关闭
			var index = parent.layer.getFrameIndex(window.name);
			parent.layer.close(index);
		   }
		 function submitFunction() {
        /*  if(photoUrl==''||photoUrl==null){
             layer.msg('图片不能为空!', {
					icon : 2
				});
            return false; 
        }*/
         if(arr==null||arr.length==0){
        	 
        	 layer.msg('图片不能为空!', {
					icon : 2
				});
        return false;  
        	 
         }
         var photoUrl=arr.toString();
		  
		 var  data={
		     "photoAlbumId":photoAlbumId,
		      "isExist":1,
		     "photoUrl":photoUrl
		      
		  };
		addTrainGuide(data);
		}
   function addTrainGuide(data) {
			$.ajax({
				type : "POST",
				dataType : "json",
				url : serverUrl.url + serverUrl.saveOrUpdatePhoto,
				data : data,
				cache : false,
				success : function(result) {
					if (result.returnCode == 0) {
						var index = parent.layer.getFrameIndex(window.name);
						parent.layer.close(index);
						//parent.showMsg(result.reason);
						//parent.getData();
						layer.msg('添加成功', {
							icon : 0
						});
					} else {
						layer.msg('' + result.reason
								+ '', {
							icon : 2
						});
					}
				},
				  error: function() {
					layer.msg('' + '添加失败!' + '', {
						icon : 2
					});
				}  
			});
		}
 script>


body>

html>

图片上传的接口 单个和批量的

package com.jysoft.core.busiInfo.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jysoft.utils.DateUtil;
import com.jysoft.utils.FileConfigUtil;
import com.jysoft.utils.GUID;
import com.jysoft.utils.RestResult;
import com.sgcc.uap.rest.annotation.RawResponseBody;

/**
 * 培训班功能模块
 * 
 * @author tdd   
 *
 */
@Controller
@RequestMapping("/fileUp")
public class FileUpController {
     
    //单个上传
	@RequestMapping("/upload")
	@RawResponseBody
	public RestResult upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
			throws IllegalStateException, IOException {
		// 判断文件是否为空,空则返回失败页面
		if (file.isEmpty()) {
			return new RestResult(1, "上传失败!");
		}
		// 获取文件存储路径(绝对路径)
		String path = System.getProperty("catalina.home") + "/webapps/" + FileConfigUtil.SHOW_PATH;
		// 获取原文件名
		String orginFileName = file.getOriginalFilename();
		String lastFileNameString = "";
	    String curFileName=GUID.UUID();
		if (null != orginFileName && !"".equals(orginFileName) && orginFileName.lastIndexOf(".") > 0) {
			lastFileNameString = orginFileName.substring(orginFileName.lastIndexOf("."), orginFileName.length());
			//curFileName=orginFileName.substring(0, orginFileName.lastIndexOf("."));
		}
		String fileName =curFileName+ lastFileNameString;
		// 创建文件实例
		File filePath = new File(path, fileName);
		// 如果文件目录不存在,创建目录
		if (!filePath.getParentFile().exists()) {
			filePath.getParentFile().mkdirs();
			System.out.println("创建目录" + filePath);
		}
		// 写入文件
		file.transferTo(filePath);
		return new RestResult(0, "上传成功!", FileConfigUtil.SHOW_PATH + fileName);
	}
	
    
    //批量上传
	@RequestMapping("/uploadList")
	@RawResponseBody
	public RestResult uploadList(@RequestParam("file") MultipartFile[] files, HttpServletRequest req)
			throws IllegalStateException, IOException {
		if (null==files||files.length==0) {
			return new RestResult(1, "上传失败!");
		}
		String fileName="";
		for(MultipartFile file:files){
			
			// 获取文件存储路径(绝对路径)
			String path = System.getProperty("catalina.home") + "/webapps/" + FileConfigUtil.SHOW_PATH;
			System.out.println("文件存储的路径"+path);
			// 获取原文件名
			String orginFileName = file.getOriginalFilename();
			String lastFileNameString = "";
		    String curFileName=GUID.UUID();
			if (null != orginFileName && !"".equals(orginFileName) && orginFileName.lastIndexOf(".") > 0) {
				lastFileNameString = orginFileName.substring(orginFileName.lastIndexOf("."), orginFileName.length());
				System.out.println("字符串"+lastFileNameString);
				//curFileName=orginFileName.substring(0, orginFileName.lastIndexOf("."));
			}
		    fileName =curFileName+ lastFileNameString;
		    System.out.println("文件名"+fileName);
			// 创建文件实例
			File filePath = new File(path, fileName);
			// 如果文件目录不存在,创建目录
			if (!filePath.getParentFile().exists()) {
				filePath.getParentFile().mkdirs();
				System.out.println("创建目录" + filePath);
			}
			// 写入文件
			file.transferTo(filePath);
		}
		
		return new RestResult(0, "上传成功!", FileConfigUtil.SHOW_PATH + fileName);
 
	}

}

存入数据库的方法 增删改差

/// 增删班级照片
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveOrUpdatePhoto", method = { RequestMethod.GET, RequestMethod.POST })
	@RawResponseBody
	public RestResult saveOrUpdatePhoto(HttpServletRequest request, HttpSession session) {
		try {
			SessionUtils sessionUtils = new SessionUtils(request);
			Map<String, Object> paramsMap = RequestUtil.getParameterMap(request);
			if (null == paramsMap || paramsMap.size() == 0) {
				return new RestResult(1, "操作失败!");
			}
			Object photoId = paramsMap.get("photoId");
			Object photoUrl = paramsMap.get("photoUrl");
			Object del = paramsMap.get("del");
			String userIdString = (String) sessionUtils.getValue("loginUserId");
			  String[] urlArray=null;
			TClassPhoto classPhoto = new TClassPhoto();
            if(null!=photoUrl&&!"".equals(photoUrl)){
            String  photoUrlString=String.valueOf(photoUrl);
            urlArray=photoUrlString.split(",");
            }
            boolean  isOption=false;
			if((null!=urlArray&&urlArray.length>0)){
				 for(String url:urlArray){
					 paramsMap.put("photoUrl", url);
					 classPhoto = ConvertModeUtil.convertMapToBean(TClassPhoto.class, paramsMap);
					 if (null != photoId && !"".equals(photoId)) {
							TClassPhoto oldDate = photoBizc.get(String.valueOf(photoId));
							// 更新
							oldDate.setUpdateDate(DateUtil.getCurrentDate());
							oldDate.setUpdateBy(userIdString);
							CopyUtils.copyPropertiesIgnoreNull(classPhoto, oldDate);
							if (null != del && "1".equals(String.valueOf(del))) {
								oldDate.setIsExist("0");
							}
							photoBizc.update(oldDate, String.valueOf(photoId));
						} else {
							Object photoAlbumId = paramsMap.get("photoAlbumId");
							String errorString = "";
							if (photoAlbumId == null) {
								errorString = "添加失败,操作异常!";
							}
							if (null != errorString && !"".equals(errorString)) {

								return new RestResult(1, errorString);
							}
							classPhoto.setCreateBy(userIdString);
							classPhoto.setPhotoAlbumId(String.valueOf(photoAlbumId));
							classPhoto.setCreateDate(DateUtil.getCurrentDate());
							classPhoto.setIsExist("1");
							photoBizc.add(classPhoto);
						} 
				 }
			}
			if(null!=del){
				if (null != photoId && !"".equals(photoId)) {
					TClassPhoto oldDate = photoBizc.get(String.valueOf(photoId));
					// 更新
					oldDate.setUpdateDate(DateUtil.getCurrentDate());
					oldDate.setUpdateBy(userIdString);
					CopyUtils.copyPropertiesIgnoreNull(classPhoto, oldDate);
					if (null != del && "1".equals(String.valueOf(del))) {
						oldDate.setIsExist("0");
					}
					photoBizc.update(oldDate, String.valueOf(photoId));
				}  
			}
			return new RestResult(0, "操作成功!");
		} catch (

		Exception e) {
			e.printStackTrace();
			return new RestResult(1, "操作失败!");
		}
	}

						classPhoto.setIsExist("1");
						photoBizc.add(classPhoto);
					} 
			 }
		}
		if(null!=del){
			if (null != photoId && !"".equals(photoId)) {
				TClassPhoto oldDate = photoBizc.get(String.valueOf(photoId));
				// 更新
				oldDate.setUpdateDate(DateUtil.getCurrentDate());
				oldDate.setUpdateBy(userIdString);
				CopyUtils.copyPropertiesIgnoreNull(classPhoto, oldDate);
				if (null != del && "1".equals(String.valueOf(del))) {
					oldDate.setIsExist("0");
				}
				photoBizc.update(oldDate, String.valueOf(photoId));
			}  
		}
		return new RestResult(0, "操作成功!");
	} catch (

	Exception e) {
		e.printStackTrace();
		return new RestResult(1, "操作失败!");
	}
}

你可能感兴趣的:(前端)