Springboot与Vue整合,实现文件上传与下载功能

Springboot与Vue整合,实现文件上传与下载功能

yml相关配置:

# 自定义属性(文件上传/下载路径,可配置参数)
download:
  filePath: D:\\MyComputer\\小辰哥哥\\

1.文件下载功能

后端控制器代码:

package com.kd.opt.controller;

import com.kd.opt.util.OptDataUtil;
import com.kd.opt.util.ReturnDataUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 关于文件上传与下载
 *
 * @author 小辰哥哥
 */
@RestController
@CrossOrigin
@RequestMapping("/fileOperationController")
public class FileOperationController {

    // 文件上传/下载路径(可配置参数)
    @Value("${download.filePath}")
    private String filePath;

    /**
     * 文件下载
     *
     * @param fileName
     * @return
     * @author 小辰哥哥
     */
    @PostMapping("/download")
    public byte[] downloadFile(@RequestParam("fileName") String fileName) {
        // 关联文件
        File file = new File(filePath + fileName);
        byte[] fileBytes = null;
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream bos = null;
        try {
            fileInputStream = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = fileInputStream.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            fileBytes = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileBytes;
    }
}

前端Vue代码:

<el-button type="warning" round @click="download">下载按钮</el-button>
// download方法
download() {
   var params = new URLSearchParams();
   params.append("fileName", "小辰哥哥.docx");

   this.$axios({
   	  // 根据自己项目情况如实填写
      url: "/fileOperationController/download",
      method: "post",
      data: params,
      responseType: 'blob',
   }).then(data => {
   	  // 获取数据(重点如何处理数据)
      var response = data.data;
      let url = window.URL.createObjectURL(new Blob([response]));
      let a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      // 设置新文件名称(注意文件后缀名)
      a.setAttribute('download', '小辰哥哥我爱你.docx');
      document.body.appendChild(a);
      // 点击下载
      a.click();
      // 下载完成移除元素
      document.body.removeChild(a);
      // 释放掉blob对象
      window.URL.revokeObjectURL(url);
   }).catch(error => {
      this.$message({message: '网络连接异常', type: 'error'});
   })
}

文件所在位置:
在这里插入图片描述
开始测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.文件上传功能

后端控制器代码:

package com.kd.opt.controller;

import com.kd.opt.util.OptDataUtil;
import com.kd.opt.util.ReturnDataUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 关于文件上传与下载
 *
 * @author 小辰哥哥
 */
@RestController
@CrossOrigin
@RequestMapping("/fileOperationController")
public class FileOperationController {

    // 文件上传/下载路径(可配置参数)
    @Value("${download.filePath}")
    private String filePath;

    /**
     * 文件上传
     *
     * @param fileName
     * @return
     * @author 小辰哥哥
     */
    @PostMapping("/upload")
    public OptDataUtil uploadFile(@RequestParam("file") MultipartFile fileName) {
        try {
            // 关联文件
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream writer = new FileOutputStream(new File(file, fileName.getOriginalFilename()));
            writer.write(fileName.getBytes());
            writer.flush();
            writer.close();
            return ReturnDataUtil.getSuccess("200");
        } catch (Exception e) {
            return ReturnDataUtil.getFailCodeMessage("500", "文件上传失败");
        }
    }
}

前端Vue代码(Element UI框架复用):

<el-upload
      class="upload-demo"
      :action="uploadUrl"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="3"
      :on-exceed="handleExceed"
      :file-list="fileList">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
data() {
  return {
     // 请求后端服务器的接口地址
     uploadUrl: this.$axios.defaults.baseURL+"/fileOperationController/upload",
     
     // 框架中的案例(可以忽略)
     fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
   }
},
methods: {
   // 框架中的案例(可以忽略)
   handleRemove(file, fileList) {
      console.log(file, fileList);
   },
   handlePreview(file) {
      console.log(file);
   },
   handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
   },
   beforeRemove(file, fileList) {
     return this.$confirm(`确定移除 ${ file.name }?`);
   }
}

开始测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


总结

每天一个提升小技巧!!!

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小辰哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值