Springboot3+Vue3实现文件上传下载功能

文件上传

//System.getProperty("user.dir")获取到当前项目的根路径
    //文件上传的目录路径
    private static final String filePath=System.getProperty("user.dir")+"/files";

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){//文件流的形式接受前端发送过来的文件
        String originalFilename = file.getOriginalFilename(); //xxx.png
        if (!FileUtil.isDirectory(filePath)){//如果目录不存在需要先创建目录
            FileUtil.mkdir(filePath);//创建一个files目录
        }
        //提供文件存储的完整的路径
        //给文件名加一个唯一的标识
        String fileName=System.currentTimeMillis() + "_" +originalFilename;//1234566721_xxx.png
        String realPath=filePath+fileName;
        try{
            FileUtil.writeBytes(file.getBytes(),realPath);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("500","文件上传失败");
        }
        //返回一个网络链接
        //http://localhost:8080/files/download/xxx.png
        String url="http://localhost:8080/files/download/"+fileName;
        return Result.success(url);
    }

文件下载

/**
     * 文件下载
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response){
        try {
            //response设置统一的文件名称,设置成utf-8编码
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");
            OutputStream os = response.getOutputStream();
            String realPath=filePath+fileName;//完整的文件路径
            //获取到文件的字节数组
            byte[] bytes=FileUtil.readBytes(realPath);
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("500","文件下载失败");
        }
    }
//response设置统一的文件名称,设置成utf-8编码
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");

前端对接文件上传下载

 upload组件

<el-form-item label="头像">
      <div style="width: 100%;display: flex;justify-content: center;margin-bottom: 20px">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/files/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
        >
          <img v-if="data.form.avatar" :src="data.form.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      </el-form-item>

回调函数

const handleAvatarSuccess = (res) => {
  console.log(res.data)
  data.form.avatar=res.data
}

表格里面显示图片

<el-table-column label="照片">
          <template #default="scope">
            <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" style="width: 40px;height: 40px" />
          </template>
        </el-table-column>

上传头像表单

<el-form-item label="照片">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/files/upload"
            list-type="picture"
            :on-success="handleAvatarSuccess"
        >
          <el-button type="primary">上传头像</el-button>
        </el-upload>
      </el-form-item>
const handleAvatarSuccess = (res) => {
  console.log(res.data)
  data.form.avatar=res.data
}
posted @ 2025-04-01 00:05  师大无语  阅读(448)  评论(0)    收藏  举报