Vue调用后端Spring boot 下载Java生成的SQL文件

注:以下代码参考多个博客,整理了多个大佬的成果

1. Java生成sql文件

相当于在cmd执行命令

public static void exportSql(){
        StringBuffer command = new StringBuffer();
        String username = "root";// 用户名
        String password = "123";// 密码
        String host = "localhost";// 导入的目标数据库所在的主机
        String port = "3306";// 使用的端口号
        String exportDatabaseName = "student_manage";// 导入的目标数据库的名称
        String exportPath = "F:/student_manage.sql";// 导入的目标文件所在的位置

        // 密码是用的小p,而端口是用的大P。
        command.append("mysqldump -u").append(username).append(" -p").append(password)
                .append(" -h").append(host).append(" -P").append(port)
                .append(" ").append(exportDatabaseName).append(" -r ").append(exportPath);
        Runtime runtime = Runtime.getRuntime();
        // 这里其实是在命令窗口中执行的 command 命令行
        try {
            Process exec = runtime.exec(command.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

2. Spring boot 提供一个返回sql文件内容的接口

接口信息如下

//controller层
@GetMapping("/sql/download")
@ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        return userService.downloadFile(request,response);
    }
//service层
public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 获取指定目录下的第一个文件
        File scFileDir = new File("F://sql");
        File TrxFiles[] = scFileDir.listFiles();
        System.out.println(TrxFiles[0]);
        String fileName = TrxFiles[0].getName(); //下载的文件名

        // 如果文件名不为空,则进行下载
        if (fileName != null) {
            //设置文件路径
            String realPath = "F://sql";
            File file = new File(realPath, fileName);

            // 如果文件名存在,则进行下载
            if (file.exists()) {

                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download the song successfully!");
                } catch (Exception e) {
                    System.out.println("Download the song failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

3. Vue前端调用接口,并下载文件

代码如下

<template>
  <div>
    <Card class="vertical-container">
      <div style="text-align:center">
        <img src="@/assets/images/mysql.jpg">
        <i-button type="primary" style="font-size: 25px" @click="exportSQL">下载数据库备份文件</i-button>
      </div>
    </Card>

  </div>
</template>

<script>
  import * as userApi from '@/api/user'

  export default {
    name: "data",
    data: {
      return: {}
    },
    methods: {
      download: function(filename, text){
          var element = document.createElement('a');
          element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
          element.setAttribute('download', filename);
          element.style.display = 'none';
          document.body.appendChild(element);
          element.click();
          document.body.removeChild(element);
      },
      exportSQL: function () {
        userApi.extSQL().then((res) => {
          this.download('student_manage.sql',res)
        })
      }
    }
  }
</script>

<style scoped>
  .vertical-container {
    height: 300px;
    width: 400px;
    text-align: center;
    position: absolute;
    left: 55%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
</style>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值