SpringBoot+Vue 实现图片上传以及展示的要点

SpringBoot+Vue 实现图片上传以及展示的要点

在这次项目中,我才用springboot+vue实现图片的上传与下载:

  1. 使用后端进行图片的上传(存储在后端的文件夹中/服务器文件夹):
    下面代码中,实现了随机产生一个文件名,以防重复出现造成错误:
    文件会被存储在E盘的指定文件夹中,以随机名称的方式出现
//实体类:
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="xxxTable对象", description="")
public class DamTable implements Serializable {

    private static final long serialVersionUID=1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private String lastName;

    private String address;

    private Integer classId;

    private LocalDateTime gmtCreated;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime gmtModified;

    @ApiModelProperty(value = "图片地址字段映射")
    private String imgAddress;

}

@PostMapping("/addCoverPic/{Id}")
    public Result addCoverPic(@PathVariable (name = "Id")Integer damId,@RequestParam("upload") MultipartFile upload){
        String filePath="E:/xxxxx/xxx_pic/";
        File file =new File(filePath);

        if(!file.exists()){
            file.mkdirs();
        }
        String originalFileName = upload.getOriginalFilename();
        //获取原始图片的扩展名
        String newFileName = UUID.randomUUID()+originalFileName;
        String newFilePath = filePath+newFileName;
        String newFileName2 = "/xxx_pic/"+newFileName;
        try {
            upload.transferTo(new File(newFilePath));
            //将传来的文件写入新建的文件
        }catch (IllegalStateException | IOException e) {
            //处理异常
        }
        XXXTable ar = xxxTableService.getById(Id);
        ar.setImgAddress(newFileName2);
        System.out.println(newFilePath);
        xxxTableService.saveOrUpdate(ar);

        return Result.success(newFileName);
    }
  1. 存储图片地址到数据库:
    以上过程中,使用了mybatis+plus 因此同时在service层中,直接将图片的地址也存储更新在了数据库中:
    以下显示的就是成功存储在数据库之后的内容:
    在这里插入图片描述
  2. 前端进行访问图片
    这是最重要的一点:首先前端使用的是vue+antdesign:
    将会作为表单的一列出现展示,因此这里使用column预先进行定义:
const columns = [
  {
    dataIndex: 'id',
    key: 'id',
    slots: { title: 'customTitle' },
    scopedSlots: { customRender: 'name' },
  },
    {
      title: "封面图片",
      dataIndex: "imgAddress1",
      key: "imgAddress1",
      align: "center",
      width: "15%",
      scopedSlots: {
        customRender: "imgAddress1"
      }
    },
    {
    dataIndex: 'name',
    key: 'name',
    title: '名称',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '曾用名',
    dataIndex: 'lastName',
    key: 'lastName',
  },
  {
    title: '编号',
    dataIndex: 'damNo',
    key: 'damNo',
  }
];

采用axios请求在created()方法中获取接口数据(数据中含有img_address字段的地址值)
在获取到了column的数据之后:

  1. 最最最重要的一步:
	<a-table :columns="columns" :data-source="users">
        <span slot="customTitle"><a-icon type="smile-o" /> 编号</span>
         
         <template slot="imgAddress1" slot-scope="text, record">
           <img class="coverimg" :src="'http://localhost:xxxx/'+record.imgAddress" width="100px" alt="无封面" />
         </template>
         
         <template slot="modify" slot-scope="text, record">
             <a-button type="primary" @click="showModal(record)">
                 修改
             </a-button>
         </template>
     </a-table>

一定要采用上面这种的方法来加载图片,否则图片无法展示将会成为这样:
在这里插入图片描述
在这里插入图片描述

在正确使用之后,得到如下图的结果:
在这里插入图片描述

希望大家能有所借鉴和收获!

Respect!!!

  • 7
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 前端页面 在前端页面中,使用ElementUI组件实现上传头像的功能。首先需要引入ElementUI组件库和axios库,用于发送请求。然后在Vue实例中定义一个data对象,用于存储上传头像的相关信息。 ```html <template> <div> <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeAvatarUpload" > <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> import axios from 'axios' import { Message } from 'element-ui' export default { data() { return { imageUrl: '', uploadUrl: '/api/upload' } }, methods: { beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' if (!isJPG) { Message.error('上传头像图片只能是 JPG 或 PNG 格式!') } const isLt2M = file.size / 1024 / 1024 < 2 if (!isLt2M) { Message.error('上传头像图片大小不能超过 2MB!') } return isJPG && isLt2M }, handleUploadSuccess(response, file) { this.imageUrl = URL.createObjectURL(file.raw) this.$emit('update:avatar', this.imageUrl) } } } </script> ``` 上述代码中,使用了`<el-upload>`组件实现上传头像的功能。其中,`action`属性指定了上传头像的接口地址,`show-file-list`属性为false表示不显示上传文件列表,`on-success`属性指定了上传成功后的回调函数,`before-upload`属性指定了上传前的校验函数。 在`beforeAvatarUpload`函数中,对上传的文件进行格式和大小的校验,如果不符合要求则提示用户。如果校验通过,则返回true,表示可以上传。 在`handleUploadSuccess`函数中,获取上传成功后服务器返回的图片地址,将其赋值给`imageUrl`变量,然后使用`URL.createObjectURL`方法创建一个临时的Object URL,将其赋值给`imageUrl`变量,用于在页面中显示头像。 2. 后端接口 在后端接口中,使用SpringBoot框架实现上传头像的功能。首先需要在Controller中添加一个接口,用于接收上传的头像文件。 ```java @RestController @RequestMapping("/api") public class UploadController { @Autowired private Environment env; @PostMapping("/upload") public Map<String, Object> upload(MultipartFile file) throws Exception { String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename()); String filePath = env.getProperty("spring.servlet.multipart.location") + fileName; File dest = new File(filePath); file.transferTo(dest); Map<String, Object> map = new HashMap<>(); map.put("url", "/uploads/" + fileName); return map; } } ``` 上述代码中,使用了`@PostMapping`注解指定了上传头像的接口地址为`/api/upload`,使用了`@Autowired`注解注入了`Environment`对象,用于获取上传文件的保存路径。在`upload`方法中,首先生成一个随机的文件名,然后将上传的文件保存到指定的路径中。 最后将上传成功后的文件路径返回给前端页面。 3. 图片显示 通过前面的步骤,已经实现了上传头像的功能,并将上传成功后的图片路径返回给前端页面。现在需要将图片显示在页面中。 在Vue实例中,使用`imageUrl`变量存储上传成功后的图片路径。然后将该变量绑定到`<img>`标签的`src`属性上,用于显示上传的头像。 ```html <img v-if="imageUrl" :src="imageUrl" class="avatar"> ``` 如果上传的头像图片比较大,可能会造成页面加载缓慢,影响用户体验。为了提高页面加载速度,可以使用懒加载的方式加载图片,只有当图片进入可视区域时才进行加载。 Vue提供了`v-lazy`指令,可以实现图片的懒加载。只需要将`v-lazy`指令绑定到`<img>`标签的`src`属性上,然后在`<img>`标签上添加一个`lazy`类,就可以实现图片的懒加载。 ```html <img v-if="imageUrl" v-lazy="imageUrl" class="avatar lazy"> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Daniel_Smith

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

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

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

打赏作者

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

抵扣说明:

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

余额充值