基于Springboot+vue如何实现图片上传至数据库并显示

发布时间:2023-05-19 16:02:54 作者:iii
来源:亿速云 阅读:113

基于Springboot+vue如何实现图片上传至数据库并显示

在现代Web应用中,图片上传和显示是一个常见的需求。本文将介绍如何使用Spring Boot和Vue.js实现图片上传至数据库并显示的功能。我们将通过前后端分离的方式来实现这一功能。

1. 技术栈

2. 后端实现

2.1 创建Spring Boot项目

首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr来快速生成项目结构。选择以下依赖:

2.2 配置数据库

application.properties文件中配置数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/image_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update

2.3 创建实体类

创建一个实体类Image,用于存储图片信息:

@Entity
public class Image {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Lob
    private byte[] data;

    // Getters and Setters
}

2.4 创建Repository

创建一个ImageRepository接口,继承JpaRepository

public interface ImageRepository extends JpaRepository<Image, Long> {
}

2.5 创建Controller

创建一个ImageController,用于处理图片上传和获取请求:

@RestController
@RequestMapping("/api/images")
public class ImageController {

    @Autowired
    private ImageRepository imageRepository;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            Image image = new Image();
            image.setName(file.getOriginalFilename());
            image.setData(file.getBytes());
            imageRepository.save(image);
            return ResponseEntity.ok("Image uploaded successfully");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload image");
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Long id) {
        Optional<Image> imageOptional = imageRepository.findById(id);
        if (imageOptional.isPresent()) {
            Image image = imageOptional.get();
            return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(image.getData());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
}

3. 前端实现

3.1 创建Vue.js项目

使用Vue CLI创建一个新的Vue.js项目:

vue create image-upload-frontend

3.2 安装Axios

在Vue项目中安装Axios,用于发送HTTP请求:

npm install axios

3.3 创建图片上传组件

src/components目录下创建一个ImageUpload.vue组件:

<template>
  <div>
    <input type="file" @change="handleFileUpload" />
    <button @click="uploadImage">Upload</button>
    <div v-if="imageUrl">
      <img :src="imageUrl" alt="Uploaded Image" />
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      imageUrl: ''
    };
  },
  methods: {
    handleFileUpload(event) {
      this.file = event.target.files[0];
    },
    async uploadImage() {
      const formData = new FormData();
      formData.append('file', this.file);

      try {
        const response = await axios.post('http://localhost:8080/api/images/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        alert(response.data);
        this.fetchImage();
      } catch (error) {
        alert('Failed to upload image');
      }
    },
    async fetchImage() {
      try {
        const response = await axios.get('http://localhost:8080/api/images/1', {
          responseType: 'arraybuffer'
        });
        const blob = new Blob([response.data], { type: 'image/jpeg' });
        this.imageUrl = URL.createObjectURL(blob);
      } catch (error) {
        alert('Failed to fetch image');
      }
    }
  }
};
</script>

3.4 在App.vue中使用组件

src/App.vue中使用ImageUpload组件:

<template>
  <div id="app">
    <ImageUpload />
  </div>
</template>

<script>
import ImageUpload from './components/ImageUpload.vue';

export default {
  components: {
    ImageUpload
  }
};
</script>

4. 运行项目

4.1 启动后端

在Spring Boot项目的根目录下运行:

mvn spring-boot:run

4.2 启动前端

在Vue项目的根目录下运行:

npm run serve

5. 测试功能

打开浏览器,访问http://localhost:8081,选择一张图片并上传。上传成功后,页面将显示上传的图片。

6. 总结

本文介绍了如何使用Spring Boot和Vue.js实现图片上传至数据库并显示的功能。通过前后端分离的方式,我们可以轻松地实现这一常见的Web应用需求。希望本文对你有所帮助!

推荐阅读:
  1. 基于springboot和docker-java怎么实现对docker容器的动态管理和监控功能
  2. springboot应用实例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot vue 数据库

上一篇:如何使用springboot及vue实现垃圾分类管理系统

下一篇:vue怎么定义数组

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》