SpringBoot+Vue 实现图片上传以及展示的要点
SpringBoot+Vue 实现图片上传以及展示的要点
在这次项目中,我才用springboot+vue实现图片的上传与下载:
- 使用后端进行图片的上传(存储在后端的文件夹中/服务器文件夹): 下面代码中,实现了随机产生一个文件名,以防重复出现造成错误: 文件会被存储在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); }
- 存储图片地址到数据库: 以上过程中,使用了mybatis+plus 因此同时在service层中,直接将图片的地址也存储更新在了数据库中: 以下显示的就是成功存储在数据库之后的内容:
- 前端进行访问图片: 这是最重要的一点:首先前端使用的是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的数据之后:
- 最最最重要的一步:
<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!!!
上一篇:
通过多线程提高代码的执行效率例子