SpringBoot文件上传

SpringBoot文件上传

前言:本文环境为SpringBoot+thymeleaf+layui,上传一个MP3文件

导入依赖


<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

编写配置

server:
  port: 9000
spring:
  thymeleaf:
    cache: false  #关闭thymeleaf的缓存
  application:
    name: imooc-video-admin

  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/imooc_video_dev?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  servlet:
    multipart:		#设置文件上传的最大值
      max-file-size: 20MB
      max-request-size: 20MB

编写前端页面demo.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
    <button type="button" class="layui-btn" id="test1" name="file" style="margin-left: 110px;margin-bottom: 15px" >
        <i class="layui-icon">&#xe67c;</i>上传音乐文件
    </button>

<script src="https://www.layuicdn.com/layui/layui.js"></script>
<script>
    layui.use('upload', function(){
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#test1' //绑定元素
            ,accept: 'audio'    //规定该按钮只能上传什么类型的文件
            ,url: '/admin/bgm/bgmUpload' //上传接口
            ,done: function(res){
                //上传完毕回调
                console.log(res);
                var url = "http://localhost:9000"+res.data;
                $("#bgmContent").html("<a href='"+url+"' target='_blank' style='text-decoration: underline'>点我播放</a>");
                $("#path").attr("value",res.data);
            }
            ,error: function(){
                //请求异常回调
                alert("上传文件出现错误");
            }
        });
    });
</script>
</body>
</html>

编写Controller

package com.gt.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gt.admin.entity.Bgm;
import com.gt.admin.service.impl.BgmServiceImpl;
import com.gt.admin.utils.Layui;
import com.gt.admin.utils.R;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
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.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("/admin/bgm")
public class BgmController {
    @Autowired
    private BgmServiceImpl bgmService;
   	  @RequestMapping("/demo")
        public String demo(){
       	return "demo";
    }
    @PostMapping("/bgmUpload")
    @ResponseBody
    public R addBgm(@RequestParam("file") MultipartFile[] files) throws IOException {
        //文件保存的命名空间
        String fileSpace = "C:" + File.separator + "imooc_videos_dev";
        //文件在数据库中的路径
        String uploadPathDB = File.separator + "bgm";

        FileOutputStream fileOutputStream =null;
        InputStream inputStream =null;
        //判断文件是否为空
        try {
            if(files!= null && files.length>0){
                //获取文件的名字 eg: C:/a.txt -> a.txt
                 String fileName = files[0].getOriginalFilename();
                //判空
                if(StringUtils.isNotBlank(fileName)){
                    //文件上传的最终保存路径
                    String finalPath = fileSpace + uploadPathDB + File.separator + fileName;
                    //设置数据库的保存路径
                    uploadPathDB += (File.separator + fileName);

                    File outFile = new File(finalPath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
                        // 创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream,fileOutputStream);
                }
            }else {
                return R.error("上传出错");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传出错");
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
        }
        return R.ok().put("data",uploadPathDB);
    }
   
}

Bgm实体类这里就不列出来了,大家可以自己去编写

演示结果

上传之前的文件夹

点击上传按钮并上传一首MP3之后

最后:这里只是保存了bgm文件到文件中,如果需要保存bgm信息到数据库中,应在前端编写表单获取bgm信息保存到数据库.

posted @ 2020-09-13 17:58  毕竟是曾经  阅读(289)  评论(0编辑  收藏  举报