图像上传功能实现

一、后端

文件存放在images.path路径下

复制代码
package com.like.common;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 本地文件上传下载
 */
@RestController
@RequestMapping("/common")
@CrossOrigin
public class CommonController {
     @Value("${images.path}")
     private String basePath;

     /**
      * 文件上传
      * @param file
      * @return
      */
     @PostMapping("/upload")
     public CommonDto<String> upload(MultipartFile file){
          //原始文件名
          String originalFilename = file.getOriginalFilename();
          String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
          //使用UUID重新生成一个文件名,防止文件名重复,造成文件覆盖
          String fileName = UUID.randomUUID().toString() + suffix;
          //创建一个目录
          File dir = new File(basePath);
          //判断当前目录是否存在
          if(!dir.exists()){
               //如果目录不存在就直接创建
               dir.mkdirs();
          }
          try {
               //将临时文件转存到指定位置
               file.transferTo(new File(basePath + fileName));
          } catch (IOException e) {
               e.printStackTrace();
          }
          CommonDto<String> commonDto = new CommonDto<>();
          commonDto.setContent(fileName);
          return commonDto;
     }


     /**
      * 文件下载接口
      */
     @GetMapping("/download")
     public void download(String name, HttpServletResponse response){
          try {
               //输入流,通过输入流读取文件内容
               FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
               //输出流 通过输出流将文件返回给浏览器,在浏览器中展示图片
               ServletOutputStream outputStream = response.getOutputStream();
               response.setContentType("/image/jpeg");
               int len = 0;
               byte[] bytes = new byte[1024];
               while((len = fileInputStream.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                    outputStream.flush();
               }
               //关闭资源
               outputStream.close();
               fileInputStream.close();
          } catch (Exception e) {
               e.printStackTrace();
          }
     }
}

二、前端

表格元素里面添加如下代码

复制代码
   <el-table-column label="头像">
          <template slot-scope="scope">
            <el-popover
                placement="top-start"
                trigger="hover">
              <img :src="scope.row.avatar" style="width: 150px; height: 150px;">
              <img :src="scope.row.avatar" slot="reference" style="width: 50px; height: 50px;">
            </el-popover>
          </template>
        </el-table-column>

新增和修改表单里添加如下代码

复制代码
<!--        头像-->
        <el-form-item label="头像" :label-width="formLabelWidth" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:3333/common/upload?module=avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

methods里写handleAvatarSuccess逻辑

复制代码
 handleAvatarSuccess(res, file) {
      this.form.avatar = `http://localhost:3333/common/download?name=${res.content}`
      //手动触发一头像字段的校验
      this.$refs.foreName.validateField('avatar');

      //强制刷新
      this.$forceUpdate();
    },

三、效果如下

至此整个项目的开发工作全部完结

相关推荐
Lhappy嘻嘻4 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
伊玛目的门徒5 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
懒鸟一枚7 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
我命由我123459 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑9 小时前
Sentinel安装
java·后端·微服务
碎碎念_4929 小时前
SpringBoot + Vue 前后端分离从 0 到 1 完整环境配置流程
vue.js·spring boot·后端
shuaijie051810 小时前
强制修改调用接口的api地址。
javascript·vue.js·ecmascript
凤凰院凶涛QAQ11 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
掘金_答案11 小时前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
猿与禅12 小时前
CosId 分布式 ID 生成器完全教程:从架构原理到生产落地
java·shardingsphere·雪花算法·分布式id·高性能·cosid·号段模式