Springboot+Vue后台管理系统-文件上传功能实现

x33g5p2x  于2022-02-07 转载在 Vue.js  
字(2.5k)|赞(0)|评价(0)|浏览(490)

首先在后端新建一个controller:

代码:

package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import com.example.demo.common.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/files")
public class FileController {

    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {    // MultipartFile:用来接受前端传过来的对象
        String originalFilename = file.getOriginalFilename(); // 获取文件名称
        String rootFilePath = System.getProperty("user.dir")+"/src/main/resources/files/"+originalFilename;  //文件夹绝对路径
        // 输入输出流:huttol提供
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        return Result.success();
    }
}

我们这里使用了hutool工具类里面封装的方法,可以直接文件上传

在代码中都写好了注释,同时我们需要新建一个files文件夹用来存放文件

然后我们使用postman测试:

测试成功!后端已经写好了接口

下载接口:

/**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

postman测试:

然后将data地址搜索就会自动下载图片

然后写前台代码:

首先新增图片展示:

使用element-plus中的图片和上传就可以实现:

<el-form-item label="封面">
            <el-upload ref="upload" action="http://localhost:8099/files/upload" :on-success="filesUploadSuccess">
              <el-button  type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>

展示:

<el-table-column
          label="封面">
      <template #default="scope">
        <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
            :initial-index="4"
            fit="cover"
        >
        </el-image>
      </template>
      </el-table-column>

相关文章