图像上传功能实现

一、后端

文件存放在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();
    },

三、效果如下

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

相关推荐
李慕婉学姐6 小时前
【开题答辩过程】以《基于JAVA的校园即时配送系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·开发语言·数据库
XTTX1107 小时前
Vue3+Cesium教程(36)--动态设置降雨效果
前端·javascript·vue.js
奋进的芋圆8 小时前
Java 延时任务实现方案详解(适用于 Spring Boot 3)
java·spring boot·redis·rabbitmq
sxlishaobin8 小时前
设计模式之桥接模式
java·设计模式·桥接模式
model20058 小时前
alibaba linux3 系统盘网站迁移数据盘
java·服务器·前端
荒诞硬汉8 小时前
JavaBean相关补充
java·开发语言
提笔忘字的帝国8 小时前
【教程】macOS 如何完全卸载 Java 开发环境
java·开发语言·macos
2501_941882489 小时前
从灰度发布到流量切分的互联网工程语法控制与多语言实现实践思路随笔分享
java·开发语言
華勳全栈9 小时前
两天开发完成智能体平台
java·spring·go
alonewolf_999 小时前
Spring MVC重点功能底层源码深度解析
java·spring·mvc