SpringBoot+Vue图片上传和显示

一、后端代码:
1、在application.yml文件中写入:

files:
  upload:
    path: D:/.Projects/files/  #存放文件的自定义路径

2、新建一个Controller文件
在这里插入图片描述
3、对应代码:
(1)添加hutool工具类

<!--        hutool工具类-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.7</version>
        </dependency>

(2)上传图片代码


import cn.hutool.core.io.FileUtil;
//@Value注解是springframework下的注解
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.springbootinit.mapper.DatasMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传
 */

@RestController
@RequestMapping("/file")
public class FileController {

	//将该文件夹的路径赋值给fileUploadPath
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private DatasMapper datasMapper;

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     * 对应与前端图片上传路径:http://localhost:8081/file/upload/img
     */
    @PostMapping("/upload/img")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);       //后缀
        long size = file.getSize();                 //文件大小
        //先存储到磁盘
        File uploadParentFile = new File(fileUploadPath);
        //判断配置的文件目录是否存在,若不存在则创建一个新的文件目录
        if (!uploadParentFile.exists()){
            uploadParentFile.mkdirs();
        }
        //定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUUID);
        //文件路径与下载接口路径一样
        String url = "http://localhost:8081/file/" + fileUUID;
        //把获取到的文件存储到磁盘目录
        file.transferTo(uploadFile);
//
//        //存入数据库   根据自己项目的需求
//        Data_Resource data_resource = new Data_Resource();      //数据库实体类
//        data_resource.setR_name(originalFilename);
//        datasMapper.Insert_res(data_resource);
        return url;
    }

    /**
     * 通过流的形式下载
     * @param fileUUID
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        //设置输出流格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Context-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");
        //读取字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}

二、前端代码:
采用element组件库,
1、组件显示:(action=“url”–url是指图片上传路径)

          <el-upload
            class="avatar-uploader"
            action="http://localhost:8081/file/upload/img"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="ruleForm.avator" :src="ruleForm.avator" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

2、style中css样式设计

<style scoped>
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  font-size: 28px;
  color: #8c939d;
  width: 250px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar-uploader-icon:hover {
  border-color: #409eff;
}
.avatar {
  width: 250px;
  height: 150px;
  display: block;
}
  </style>

3、script中的函数以及数据的定义(对于数据内容可以使用“console.log(‘数据’);”进行显示)

<script>
export default {
  data() {
    return {
      ruleForm: {
        avator: "",
        }
      }
  },
  methods: {
    handleAvatarSuccess(res) {
      //res就是文件路径
      this.ruleForm.avator = res;
    },
  },
};
</script>

三、结果显示:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 6
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot中使用Vue和Element UI来显示后端图片,可以按照以下步骤进行操作: 1. 在Spring Boot项目中,创建一个用于存储图片的文件夹,比如将其命名为"images"。 2. 将需要显示图片上传到该文件夹中。 3. 在后端编写一个Controller,用于处理图片请求。可以添加一个接口,比如"/api/image/{imageName}",用于获取某个特定图片的路径。 ```java @RestController @RequestMapping("/api/image") public class ImageController { @Value("${image.path}") private String imagePath; @GetMapping("/{imageName}") public void getImage(@PathVariable String imageName, HttpServletResponse response) throws IOException { File file = new File(imagePath + "/" + imageName); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, response.getOutputStream()); } } ``` 配置文件中的image.path属性需要指向存放图片的文件夹路径。 4. 在Vue中,使用Element UI的表格组件来显示图片。首先在Vue组件中定义一个data属性,用于保存图片数据。 ```javascript data() { return { imageUrl: '/api/image/' tableData: [] }; } ``` "imageUrl"属性用于指定获取图片的接口路径。 5. 从后端获取图片数据,在Vue组件的"mounted"生命周期中发起一个请求,获取后端返回的图片数据,并将其赋值给表格的数据属性。 ```javascript mounted() { axios.get('/api/imageData') .then(response => { let data = response.data; // 对返回的data进行处理,将图片路径拼接上指定的路径 data.forEach(item => { item.imageUrl = this.imageUrl + item.imageName; }); this.tableData = data; }) .catch(error => { console.error('Error:', error); }); } ``` 6. 在表格的列定义中,使用Element UI的"el-table-column"组件来显示图片。 ```html <el-table-column prop="imageUrl" label="图片"> <template slot-scope="scope"> <img :src="scope.row.imageUrl" width="100" height="100"> </template> </el-table-column> ``` 通过以上的步骤,就可以在Spring Boot中使用Vue和Element UI来显示后端图片了。在表格中的图片列中,会显示相应的图片

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值