springboot上传文件到指定位置

发布时间 2023-03-22 21:13:31作者: yasai

这是我现在的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ya</groupId>
    <artifactId>taiji</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>taiji</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <mybatis-plus.version>3.4.1</mybatis-plus.version>
        <jquery.version>3.5.1</jquery.version>
        <layui.version>2.5.6</layui.version>
        <locator.version>0.40</locator.version>
        <hutool.version>5.4.7</hutool.version>
        <freemark.version>2.3.30</freemark.version>
        <unbescape.version></unbescape.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
<!--            过滤sptingboot默认嵌入式tomcate插件-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>



        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>8.0.21</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <!-- hutool-all -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>

        <!-- webjars-locator -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator</artifactId>
            <version>${locator.version}</version>
        </dependency>
        <!--script src="/webjars/jquery/3.5.1/jquery.min.js"></script> -->
        <!--<script src="/webjars/jquery/jquery.min.js"></script>  -->

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>${jquery.version}</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>layui</artifactId>
            <version>${layui.version}</version>
        </dependency>

        <!-- mybatis-plus-generator -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemark.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
        </dependency>

        <dependency>
            <groupId>org.unbescape</groupId>
            <artifactId>unbescape</artifactId>
            <version>1.1.2.RELEASE</version>
        </dependency>


    </dependencies>



</project>
View Code

这是application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/taijiquan?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
    username: root
    password: 789987
    driver-class-name: com.mysql.cj.jdbc.Driver
  servlet:
    multipart:
      max-file-size: 5000MB
      max-request-size: 5000MB
  resources:
    static-locations: file:D:\image\file,classpath:/META-INF/resources/, classpath:/resources/,classpath:/static/, classpath:/public/, classpath:/templates/

  thymeleaf:
    cache: false
    suffix: .html

    jackson: #返回的日期字段的格式
      date-format: yyyy-MM-dd HH:mm:ss
      time-zone: GMT+8
      serialization:
        write-dates-as-timestamps: false # true 使用时间戳显示时间
      http:
        multipart:
          max-file-size: -1
          max-request-size: -1





mybatis-plus:
  global-config:
    db-config:
      id-type: auto
  mapper-locations: classpath:mapper/taiji/*Mapper.xml
  type-aliases-package: com.ya.taiji.entity

logging:
  level:
    com.imooc.project.dao: trace
    com.imooc.project.mapper: trace
View Code

注意:

 

配置文件里面的这个规定最大文件还有文件位置的这个servlet尽量放在最前面,否则可能会不生效

上传视频的前端代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
<!--    <link href="css/video-js.min.css" rel="stylesheet">-->
<!--    <script src="js/video.min.js"></script>-->
<!--    <script src="js/indx.js"></script>-->
    <script type="text/javascript" th:src="@{/js/video.min.js}"></script>
    <link rel="stylesheet" th:href="@{/css/video-js.min.css}">
    <script src="https://unpkg.com/mediainfo.js/dist/mediainfo.min.js" ></script>

    <style>
        #t1 tr td{height: 30px; width: 100px;}
        .box0{background-color: #e8e2e2;}
        .box1{background-color: hsla(0, 40%, 98%, 0.62);}
    </style>
    <style type="text/css">
        body{margin: 0;padding: 0;}
        #input-video,#result{
            margin: 15px;
        }
        #video{
            display: none;
        }
        video::-webkit-media-controls {
            display:none !important;
        }
    </style>
    <script>
        videojs.options.flash.swf = "js/video-js.swf";
    </script>
</head>
<body>

<!--<div class="layui-form-item">-->
<!--    <label for="row" class="layui-form-label">-->
<!--        太极拳共-->
<!--    </label>-->
<!--    <div class="layui-input-inline">-->
<!--        <input type="text" id="row" name="row" required="" lay-verify="required"-->
<!--               autocomplete="off" class="layui-input">-->
<!--    </div>-->
<!---->
<!--</div>-->
<div class="layui-form-item">
    <label class="layui-form-label">视频名称</label>
    <div class="layui-input-inline" style="width: 300px;">
        <input type="text" name="row" id="namevedio" placeholder="" class="layui-input">
    </div>

    </button>
</div>
<div class="layui-form-item">
    <label class="layui-form-label">太极拳共</label>
    <div class="layui-input-inline" style="width: 300px;">
        <input type="text" name="row" id="row" placeholder="" class="layui-input">
    </div>
    <div class="layui-form-mid"></div>
    <button type="button" class="layui-btn" id="btn1">生成
    </button>
</div>

<div class="layui-form-item">

        <div class="layui-form-item">
            <table class="layui-table" id="swtable" border="1">
                <colgroup>
                    <col width="150">
                    <col width="200">
                    <col>
                </colgroup>
                <tbody>
                <tr>
                    <td style="width: auto">开始</td>
                    <td style="width: auto">
                        <input id="begin">
                    </td>
                    <td style="width: auto"><button id="btnbeg" class="layui-btn" onclick="begin()">关键帧</button></td>
                </tr>
                <tr>
                    <td style="width: auto">结束</td>
                    <td style="width: auto">
                        <input id="end">
                    </td>
                    <td style="width: auto"><button id="btnend"  class="layui-btn" onclick="end()">关键帧</button></td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="layui-form-item">

            <table  id="t1" border="1">
            </table>


        </div>




</div>

<div class="layui-form-item">
    <label class="layui-form-label">
        <input id="input-video" class="layui-btn"  type="file" accept="video/*"  onchange="postData()"/>
        <button type="submit" class="layui-btn" id="sub">提交</button>

<!--        <button id="input-video" class="layui-btn"  type="file" accept="video/*"  onchange="postData()">-->
<!--            <i class="layui-icon">&#xe67c;</i>上传图片-->
<!--        </button>-->

    </label>
</div>









<input type="hidden" id="firstPicture" name="firstPicture" value="" />
<input type="hidden" id="role_id" name="role_id" value="1" />

<!--<div id="result"></div>-->
<!--<button id = 'btn'  onclick='btn()'>关键帧</button>-->
<!--<div id="result2" type="text"></div>-->



<div class="box" style="width: 300px"></div>


<video id="video" class="video-js vjs-default-skin" controls
       preload="auto" width="300px" height="264px" poster=""
       data-setup='{}'>
    <p class="vjs-no-js">
        To view this video please enable JavaScript, and consider upgrading to a web browser
        that <a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
    </p>
</video>

</body>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/webjars/layui/layui.all.js}"></script>
<script th:src="@{/webjars/jquery/jquery.js}"></script>
<script th:src="@{/js/common/common.js}"></script>
<script type="text/javascript">


    $("#input-video").on("change",function(e){
        console.log(e.delegateTarget.value);
        var files = e.target.files || e.dataTransfer.files;
        $("#result").text("请稍后……");
        if(files){
            file = files[0];
            var URL = window.URL || window.webkitURL;
            var videoURL = URL.createObjectURL(file);
            var myPlayer =  videojs("video");
            var info = "<p>名称:"+file.name+"</p>";
            console.log(file.name);
            info += "<p>大小:"+file.size+"</p>";
            info += "<p>类型:"+file.type+"</p>";
            myPlayer.src(videoURL);  //重置video的src
            myPlayer.load(videoURL);
            myPlayer.width($(window).width());
            $("#video").show();
            myPlayer.play();
            var timeInterval = setInterval(function(){
                if(myPlayer.duration() != 0){
                    info += "<p>时长:"+myPlayer.duration()+"秒</p>";

                    info += "<p>当前时间:"+myPlayer.currentTime().toFixed(2)+"秒</p>";
                    $("#result").html(info);
                    clearInterval(timeInterval);
                }
            },1000);


        }
        else{
            alert("不支持");
        }
    })


    window.onload=function(){
        var oRow=document.getElementById("row");
        var oBtn=document.getElementById("btn1");
        console.log("oBtn")
        console.log(oBtn)
        console.log("*************")
        var oT1=document.getElementById("t1");//表格
        //每点一次按钮相应的地方就会显示出来添加后的数据

        oT1.onclick=function(ev){
            var e=ev||window.event;
            var target=e.target||window.event.srcElement;
            var tr =$("#t1 tr")
            if(target.nodeName.toLowerCase()=="button"){
                //oT1.removeChild(target.parentNode.parentNode);
                var id=target.parentNode.parentNode.id;
                var td=$(tr[id]).find("td")
                var gjz=guanjian();
                var count=oT1.rows.length;
                var title= $(td[1]).text();
                if(title==""){
                    title=gjz;
                }else{
                    title=title+","+gjz;
                }
                $(td[1]).html(title);//给值
            }
        }
    }

    var oRow=document.getElementById("row");
    var oT1=document.getElementById("t1");//表格

    var paraMap = {};
    //登录按钮
    $("#sub").bind("click", function () {
        paraMap.url=$("#firstPicture").val();
        paraMap.startframe=$("#begin").val();
        paraMap.finishframe=$("#end").val();
        paraMap.generalmoves=$("#row").val();
        paraMap.name=$("#namevedio").val();
        paraMap.ischanges=0;
        paraMap.role_id=$("#role_id").val();
        // paraMap.name=$("#name").val();
        var keyframe="";
        for (let i = 0; i < paraMap.generalmoves; i++) {
            if(i==0){
                keyframe=$("#vas"+i).val();
            }else{
                keyframe=keyframe+"|"+$("#vas"+i).val();
            }
        }
        paraMap.keyframe=keyframe;
        $.ajax({
            type: "POST",
            url: "http://localhost:8080/train-video/add",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(paraMap),
            success: function () {
                alert("提交成功");
                window.location.href = "http://localhost:8080/train-video/trainVideoList";
            },
            error: function () {
                alert("提交  失败!")
            }
        });
    })


    //加载表格
    $("#btn1").bind("click", function () {
        if(!oRow.value){
            alert("请输入正确的数据");
        }else{
            for(var i=0;i<oRow.value;i++){
                var oTr=document.createElement("tr");
                oTr.className="box"+(i%2);
                oTr.id=i
                var idd=document.createElement("td");//附加行号
                idd.textContent=""+(i+1)+"";
                oTr.appendChild(idd);
                for(var j=0;j<1;j++){//列,其实一个就行
                    var oTd=document.createElement("td");
                    oTd.innerHTML="<input id=val"+i+" name=di"+i+" readonly='true'>"+"<input id=vas"+i+" type='hidden'>";
                    oTr.appendChild(oTd);
                }
                var oClose=document.createElement("td");//附加删除
                oClose.innerHTML="<button class=\"layui-btn layui-btn-xs\">关键帧</button>";
                oT1.appendChild(oTr);
                oTr.appendChild(oClose);
            }
        }
    })


    oT1.onclick=function(ev){
        var e=ev||window.event;
        var target=e.target||window.event.srcElement;
        var tr =$("#t1 tr")
        if(target.nodeName.toLowerCase()=="button"){
            //oT1.removeChild(target.parentNode.parentNode);
            var id=target.parentNode.parentNode.id;
            var td=$(tr[id]).find("td")
            var gjz=guanjian();
            var count=oT1.rows.length;
            //var title= $(td[1]).text();
            var title= $("#vas"+id).val();
            if(title==""){
                title=gjz;
            }else{
                title=title+","+gjz;
            }
            $("#vas"+id).val(title);
            $("#val"+id).val(title);
            //$(td[1]).html(title);//给值
        }
    }


    var videos = document.getElementsByTagName('video');
    var myvideo=videojs("video");
    myvideo.ready(function(){
        console.log("已就绪");
    });




    //模板
    shuzu=[]
    function  btn(){
        //console.log("当前播放时间为"+myvideo.currentTime());
        var info=""
        info += "<p>当前时间:"+myvideo.currentTime().toFixed(2)+"秒</p>";
        shuzu.push(myvideo.currentTime().toFixed(2))
        console.log(shuzu);
        $("#result2").html(shuzu);

        document.getElementById("result3").value=shuzu;
    }

    //开始帧
    function  begin(){
        console.log("当前播放时间为"+myvideo.currentTime());
        var info=""
        info += "<p>当前时间:"+myvideo.currentTime().toFixed(2)+"秒</p>";

        console.log(myvideo.currentTime().toFixed(2));
        $("#begin").html(myvideo.currentTime().toFixed(2));

        document.getElementById("begin").value=myvideo.currentTime().toFixed(2);
    }

    //结束帧
    function  end(){
        console.log("当前播放时间为"+myvideo.currentTime());
        var info=""
        info += "<p>当前时间:"+myvideo.currentTime().toFixed(2)+"秒</p>";
        console.log(myvideo.currentTime().toFixed(2));
        $("#end").html(myvideo.currentTime().toFixed(2));

        document.getElementById("end").value=myvideo.currentTime().toFixed(2);
    }

    //获取一个关键帧
    function  guanjian(){
        console.log("当前播放时间为"+myvideo.currentTime());

        var info=""
        info += "<p>当前时间:"+myvideo.currentTime().toFixed(2)+"秒</p>";
        return myvideo.currentTime().toFixed(2);
    }

    function add1(){
        var shi = document.getElementById("shi");
        console.log(shi.value);
        alert(shi.value)

    }

    function inpu(){
        var tijiao=[];
        var begg=$("#begin").text();
        tijiao.push(begg);
        var endd=$("#end").text();
        tijiao.push(endd);
        console.log(tijiao)
    }

    function postData () {
        var formData = new FormData();
        formData.append("file", $("#input-video")[0].files[0]);
        $.ajax({
            //url: '/train-video/updateFile',
            url: "http://localhost:8080/train-video/updateFile",
            type: "POST",
            data: formData,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            dataType: 'text',
            success: function (data) {
                $("#firstPicture").attr("value", data);
            },
            error: function (data) {

            }
        });
    }
</script>
</html>
View Code

代码写的有点连,主要就是使用ajax调用controller

上传文件的controller:

package com.ya.taiji.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ya.taiji.entity.Student;
import com.ya.taiji.entity.TrainVideo;
import com.ya.taiji.service.TrainVideoService;
import com.ya.taiji.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ya
 * @since 2023-02-14
 */
@Controller
@RequestMapping("/train-video")
public class TrainVideoController {

    @Autowired
    private TrainVideoService trainVideoService;
    @GetMapping("ceshi")
    @ResponseBody
    public String ceshi(){
        return "ceshi";
    }

    @GetMapping("trainVideoList")
    public String toList(){
        return "/trainVideo/trainVideoList";
    }
    /**
     * 查询方法
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("list")
    @ResponseBody
    public R<Map<String,Object>> list(String name, Long page, Long limit){
        System.out.println("查询视频名称:name:"+name);
        LambdaQueryWrapper<TrainVideo> wrapper = Wrappers.<TrainVideo>lambdaQuery()
                .like(StringUtils.isNotBlank(name), TrainVideo::getName, name)
                .orderByDesc(TrainVideo::getId);
        Page<TrainVideo> mypage = trainVideoService.page(new Page<>(page, limit), wrapper);
        return ResultUtil.buildPageR(mypage);
    }

    /**
     * 进入新增页
     * @return
     */
    @GetMapping("toAdd")
    public String toAdd(){
        return "trainVideo/trainVideoAdd";
    }

    public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
    private static final String filePath = "D:/image/file";


    @PostMapping("updateFile")
    @ResponseBody
    public String uploadFiles2(MultipartFile file, HttpServletRequest request) {
        String oldName = file.getOriginalFilename();
        String NowDate = simpleDateFormat.format(new Date());
        String realPath = filePath + "/" + NowDate;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //利用UUID生成伪随机字符串,作为文件名避免重复
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //生成新文件名
        String newname = uuid +"-"+ oldName;
        try {
            file.transferTo(new File(folder, newname));
            return NowDate + "/" + newname;
        } catch (Exception e) {
            return "上传失败";
        }
    }


    @PostMapping("add")
    @ResponseBody
    public Integer add(@RequestBody TrainVideo trainVideo){
        trainVideoService.save(trainVideo);
        return 1;
    }
}

 

 

主要代码在这里