• layui 视频上传本地(项目)


    jsp页面:

      1 <%@ page language="java" contentType="text/html; charset=UTF-8"
      2          pageEncoding="UTF-8"%>
      3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      4 <html>
      5 <head>
      6     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      7     <title>个人资料</title>
      8     <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
      9     <script src="/static/layui/layui.js"></script>
     10     <script src="/static/js/jquery.min.js"></script>
     11     <script type="text/javascript">
     12         layui.use('upload',function(){
     13             var $ = layui.jquery
     14                 ,upload = layui.upload;
     15 
     16             upload.render({
     17                 elem: '#fileBtn'
     18                 ,url: '/uploadFiles/uploadImg'
     19                 ,accept: 'file'
     20                 ,field:"layuiFile"
     21                 ,auto: false
     22                 ,bindAction: '#uploadBtn'
     23                 ,done: function(res){
     24                     alert(res.data.src);
     25                     $("[name=userImage]").val(res.data.src);
     26                 }
     27             });
     28 
     29 
     30             //普通图片上传
     31             var uploadInst = upload.render({
     32                 elem: '#test1'
     33                 ,url: '/uploadFiles/uploadImg'
     34                 ,field:"layuiFile"
     35                 ,before: function(obj){
     36                     //预读本地文件示例,不支持ie8
     37                     obj.preview(function(index, file, result){
     38                         $('#demo1').attr('src', result); //图片链接(base64)
     39                     });
     40                 }
     41                 ,done: function(res){
     42                     //如果上传失败
     43                     if(res.code > 0){
     44                         return layer.msg('上传失败');
     45                     }
     46                     //上传成功
     47                     $("[name=img1]").val(res.data.src);
     48                 }
     49                 ,error: function(){
     50                     //演示失败状态,并实现重传
     51                     var demoText = $('#demoText');
     52                     demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
     53                     demoText.find('.demo-reload').on('click', function(){
     54                         uploadInst.upload();
     55                     });
     56                 }
     57             });
     58 
     59             //多图片上传
     60             upload.render({
     61                 elem: '#test2'
     62                 ,url: '/uploadFiles/uploadImg'
     63                 ,field:"layuiFile"
     64                 ,multiple: true
     65                 ,before: function(obj){
     66                     //预读本地文件示例,不支持ie8
     67                     obj.preview(function(index, file, result){
     68                         $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style=" 230px;height: 230px;">')
     69                     });
     70                 }
     71                 ,done: function(res){
     72                     //上传完毕
     73                 }
     74             });
     75 
     76             //上传视频
     77             var uploadInst=upload.render({
     78                 elem: '#video'
     79                 ,url: '/uploadFiles/uploadVideo'
     80                 ,field:"layuiVideo"
     81                 ,data:{"dir":"media"}
     82                 ,accept: 'video' //视频
     83                 // ,before:function (obj) {
     84                 //     $('#demo9').css('display','block').attr('src', "http://p6nngxvb7.bkt.clouddn.com/FsyjSltTtkVtzepa_w7zsnS_S7zO"); //链接(base64)http://p6nngxvb7.bkt.clouddn.com/FsyjSltTtkVtzepa_w7zsnS_S7zO
     85                 // }
     86                 ,done: function(res){
     87                     if(res.code==1){
     88                         layer.alert(res.message,5);
     89                     }
     90                     if(res.error>0){
     91                         return layer.msg(res.message);
     92                     }
     93                     if(res.error==0){
     94                         alert("res.url:"+res.url);
     95                         $("#videourl").val(res.url);
     96                         $("#demo9").attr("src",res.url);
     97                         layer.alert("上传成功",{offset:['200px','450px'],icon:6});
     98                     }
     99                 }
    100                 ,error:function () {
    101                     //演示失败状态,并实现重传
    102                     var demoText = $('#demoText');
    103                     demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
    104                     demoText.find('.demo-reload').on('click', function () {
    105                         uploadInst.upload();
    106                     });
    107                 }
    108             });
    109         });
    110     </script>
    111 
    112 </head>
    113 <body>
    114     <div class="layui-upload">
    115         <div class="layui-upload">
    116             <input type="hidden" name="userImage" required lay-verify="required" />
    117             <button type="button" class="layui-btn layui-btn-primary" id="fileBtn"><i class="layui-icon">&#xe67c;</i>选择文件</button>
    118             <button type="button" class="layui-btn layui-btn-warm" id="uploadBtn">开始上传</button>
    119         </div>
    120     </div>
    121 
    122 
    123     <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    124         <legend>常规使用:普通图片上传</legend>
    125     </fieldset>
    126     <div class="layui-upload">
    127         <input type="hidden" name="img1" required lay-verify="required" />
    128         <button type="button" class="layui-btn" id="test1">上传图片</button>
    129         <div class="layui-upload-list">
    130             <img class="layui-upload-img" id="demo1" style=" 230px;height: 230px;">
    131             <p id="demoText"></p>
    132         </div>
    133     </div>
    134 
    135 
    136     <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    137         <legend>上传多张图片</legend>
    138     </fieldset>
    139     <div class="layui-upload">
    140         <button type="button" class="layui-btn" id="test2">多图片上传</button>
    141         <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
    142             预览图:
    143             <div class="layui-upload-list" id="demo2"></div>
    144         </blockquote>
    145     </div>
    146 
    147 
    148     <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    149         <legend>指定允许上传的文件类型</legend>
    150     </fieldset>
    151     <button type="button" class="layui-btn" id="test3"><i class="layui-icon"></i>上传文件</button>
    152     <button type="button" class="layui-btn layui-btn-primary" id="test4"><i class="layui-icon"></i>只允许压缩文件</button>
    153     <button type="button" class="layui-btn" id="test5"><i class="layui-icon"></i>上传视频</button>
    154     <button type="button" class="layui-btn" id="test6"><i class="layui-icon"></i>上传音频</button>
    155 
    156 
    157     <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    158         <legend>上传视频</legend>
    159     </fieldset>
    160     <div class="layui-form-item" id="videoUp">
    161         <label class="layui-form-label" style="height: 137px; line-height: 117px">视频</label>
    162         <input name="classVideo" id="videourl"  value="" autocomplete="off" class="layui-input" type="hidden">
    163         <div class=" layui-upload-drag" id="video" style="border-left: 0px;" type="video">
    164             <i class="layui-icon">&#xe654;</i>
    165             <p>点击上传</p>
    166             <video id="demo9" src="" style="position: absolute;height: 137px; 137px;margin: -106px auto auto -60px;"/>
    167         </div>
    168         <input type="button" value="预览" onclick="openVideo()" style="margin-left: 30px">
    169     </div>
    170 </body>
    171 <script type="text/javascript">
    172     function openVideo() {
    173 
    174         var classVideo = document.getElementById("videourl").value;
    175         var index = layer.open({
    176             type: 2,
    177             content: '/uploadFiles/goLook?classVideo='+classVideo,
    178             area: ['600px', '450px'],
    179             offset:'t',
    180             maxmin: true,
    181             end: function () {
    182 
    183             }
    184         });
    185     }
    186 </script>
    187 </html>

    Controller层代码:

     1  @RequestMapping(value = "/uploadVideo",method = RequestMethod.POST)
     2     @ResponseBody
     3     public Object uploadVideo(@RequestParam("layuiVideo") MultipartFile[] layuiFile, HttpServletRequest request, HttpServletResponse response){
     4         log.info("进入wph的layui视频上传接口》》》》》》》》》》》》》》》");
     5         Map<String,Object> map=new HashMap<>();
     6         Map<String,Object> map2=new HashMap<>();
     7         KitFileUtil kitFileUtil=new KitFileUtil();
     8         map = kitFileUtil.kitFileUtil(layuiFile, request, response);
     9         String error = map.get("error").toString();
    10         if("101".equals(error)){
    11             map2.put("error",101);
    12             map2.put("message",map.get("message"));
    13             return map;
    14         }
    15         map2.put("error",0);
    16         String url[]=(String[])map.get("url");
    17         map2.put("url",url[0]);
    18         return JSONObject.toJSON(map2);
    19     }

    视频上传的工具类:

      1 package com.xw.util;
      2 
      3 import org.apache.commons.fileupload.servlet.ServletFileUpload;
      4 import org.springframework.util.FileCopyUtils;
      5 import org.springframework.web.bind.annotation.RequestParam;
      6 import org.springframework.web.multipart.MultipartFile;
      7 
      8 import javax.servlet.ServletContext;
      9 import javax.servlet.http.HttpServletRequest;
     10 import javax.servlet.http.HttpServletResponse;
     11 import java.io.File;
     12 import java.io.FileOutputStream;
     13 import java.text.SimpleDateFormat;
     14 import java.util.*;
     15 
     16 /**
     17  * 文件上传
     18  */
     19 public class KitFileUtil {
     20 
     21     private static ServletContext servletContext;
     22 
     23     public Map<String,Object> kitFileUtil(@RequestParam("imgFile") MultipartFile[] imgFile, HttpServletRequest request, HttpServletResponse response){
     24 
     25 
     26         // 文件保存目录路径
     27         String savePath = request.getSession().getServletContext().getRealPath("")  + "/"+ StaticFinalVar.IMG_FILES;
     28         System.out.println("正确路径:"+savePath);
     29 
     30         //文件保存目录URL
     31         String saveUrl  = request.getContextPath() +  "/"+ StaticFinalVar.IMG_FILES;
     32 
     33         //定义允许上传的文件扩展名
     34         HashMap<String, String> extMap = new HashMap<String, String>();
     35         extMap.put("image", "gif,jpg,jpeg,png,bmp");
     36         extMap.put("flash", "swf,flv");
     37         extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
     38         extMap.put("file", "doc,docx,xls,xlsx,ppt,txt,zip,rar,gz,bz2");
     39 
     40         //最大文件大小
     41         long maxSize = 9000000;
     42 
     43         response.setContentType("text/html; charset=UTF-8");
     44 
     45         if(!ServletFileUpload.isMultipartContent(request)){
     46             return getError("请选择文件。");
     47         }
     48         //检查目录
     49         File uploadDir = new File(savePath);
     50         if(!uploadDir.exists()){
     51             uploadDir.mkdir();
     52 //            return getError("上传目录不存在。");
     53         }
     54 
     55         //检查目录写权限
     56         if(!uploadDir.canWrite()){
     57             return getError("上传目录没有写权限。");
     58         }
     59 
     60         String dirName = request.getParameter("dir");
     61         if (dirName == null) {
     62             dirName = "image";
     63         }
     64         if(!extMap.containsKey(dirName)){
     65             return getError("目录名不正确。");
     66         }
     67 
     68         //创建文件夹
     69         savePath += dirName + "/";
     70         saveUrl += dirName + "/";
     71         File saveDirFile = new File(savePath);
     72         if (!saveDirFile.exists()) {
     73             saveDirFile.mkdirs();
     74         }
     75         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
     76         String ymd = sdf.format(new Date());
     77         savePath += ymd + "/";
     78         saveUrl += ymd + "/";
     79         File dirFile = new File(savePath);
     80         if (!dirFile.exists()) {
     81             dirFile.mkdirs();
     82         }
     83         String url[] = new String[imgFile.length];
     84         Map<String,Object> map = new HashMap<String, Object>();
     85         for (int i=0;i<imgFile.length;i++) {
     86             System.out.println(imgFile[i]);
     87 
     88             // 获取上传文件的名字
     89             String fileName = imgFile[i].getOriginalFilename();
     90             // 获取长度
     91             long fileSize = imgFile[i].getSize();
     92 
     93             if(!imgFile[i].isEmpty()){
     94 
     95                 // 检查文件大小
     96                 if(imgFile[i].getSize() > maxSize){
     97                     return getError("上传文件大小超过限制。");
     98                 }
     99 
    100                 // 检查扩展名
    101                 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    102                 if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
    103                     return getError("上传文件扩展名是不允许的扩展名。
    只允许" + extMap.get(dirName) + "格式。");
    104                 }
    105 
    106                 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    107                 String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
    108                 try{
    109                     // 保存文件
    110                     System.out.println(saveUrl + newFileName);
    111                     FileCopyUtils.copy(imgFile[i].getInputStream(), new FileOutputStream(savePath + newFileName));
    112 
    113                 }catch(Exception e){
    114                     return getError("上传文件失败。");
    115                 }
    116 
    117 
    118 
    119                 url[i] = saveUrl + newFileName;
    120 //                map.put("error", 0);
    121 //                map.put("url", saveUrl + newFileName);
    122 //                return map;
    123             }
    124         }
    125         map.put("error", 0);
    126         map.put("url", url);
    127         return map;
    128 //        return getError("服务器端错误。");
    129     }
    130 
    131     private Map<String,Object> getError(String message) {
    132         Map<String,Object> map = new HashMap<String, Object>();
    133 //
    134         map.put("error", 101);
    135         map.put("message", message);
    136         return map;
    137     }
    138 
    139 }

    效果图:

    Controller层预览跳转:

     1 //跳转预览页面
     2     @RequestMapping(value = "/goLook", method = RequestMethod.GET)
     3     public Object goLook(HttpServletRequest request, HttpSession session){
     4         log.info("课堂管理 》预览");
     5 
     6         ModelAndView mv = new ModelAndView();
     7         String classVideo = request.getParameter("classVideo");
     8         mv.addObject("kitG", classVideo);
     9         mv.setViewName("yulan");
    10         return mv;
    11     }

    预览页面:

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <%
     3     String path = request.getContextPath();
     4     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
     7 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
     8 <!DOCTYPE html>
     9 <html lang="en">
    10 
    11 <head>
    12     <meta charset="UTF-8">
    13     <meta name="viewport" content="width=device-width, initial-scale=1.0">
    14     <meta http-equiv="X-UA-Compatible" content="ie=edge">
    15     <title>图片上传</title>
    16     <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    17     <script src="/static/layui/layui.js"></script>
    18     <script src="/static/js/jquery.min.js"></script>
    19 </head>
    20 
    21 <body>
    22 <div class="kit-doc">
    23     </div>
    24     <!--这里写页面的代码-->
    25     <h1>h5 video</h1>
    26     <div id="box">
    27         <video id="video" controls preload="auto" width="400px" height="300px">
    28             <source src="${kitG}" type="video/mp4">
    29         </video>
    30     </div>
    31 
    32 
    33 </div>
    34 
    35 <script>
    36     layer.open({
    37         type: 1,
    38         title: false,
    39         shadeClose: true,
    40         area: ['400px', '350px'],
    41         content: $('#box'),
    42         success: function(layero){
    43             //layer样式layer-anim导致全屏样式错乱,移除该样式即可
    44             setTimeout(function() {
    45                 $(layero).removeClass('layer-anim');
    46             }, 0);
    47         }
    48     });
    49 </script>
    50 
    51 </body>
    52 
    53 </html>
  • 相关阅读:
    bootstrap里的下拉菜单
    bootstrap里的图标
    bootstrap
    maven和svn区别
    maven
    计算机程序的思维逻辑 (20)
    计算机程序的思维逻辑 (19)
    计算机程序的思维逻辑 (18)
    计算机程序的思维逻辑 (17)
    计算机程序的思维逻辑 (15)
  • 原文地址:https://www.cnblogs.com/wangpeihua/p/9525521.html
Copyright © 2020-2023  润新知