springboot+vue+mybatis-plus以表格形式显示书籍id对应的照片代码实现
时间: 2023-08-01 15:10:24 浏览: 175
基于Springboot+Vue2+Mybatis-plus的社团信息管理系统设计源码
好的,下面是Spring Boot + Vue.js + MyBatis-Plus实现以表格形式显示书籍ID对应的照片的代码实现:
1. 创建Book实体类
```java
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String author;
private String photoUrl;
// 省略getter和setter方法
}
```
2. 创建BookMapper接口
```java
@Mapper
public interface BookMapper extends BaseMapper<Book> {
@Select("SELECT photo_url FROM book WHERE id = #{bookId}")
String getPhotoUrlById(Long bookId);
}
```
3. 创建BookService接口和实现类
```java
public interface BookService {
List<Book> getAllBooks();
String getPhotoUrlById(Long bookId);
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public List<Book> getAllBooks() {
return bookMapper.selectList(null);
}
@Override
public String getPhotoUrlById(Long bookId) {
return bookMapper.getPhotoUrlById(bookId);
}
}
```
4. 创建BookController类
```java
@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping("")
public List<Book> getAllBooks() {
return bookService.getAllBooks();
}
@GetMapping("/{bookId}/photo")
public String getPhotoUrlById(@PathVariable Long bookId) {
return bookService.getPhotoUrlById(bookId);
}
}
```
5. 创建BookTable.vue组件
```vue
<template>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Author</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
<tr v-for="book in books" :key="book.id">
<td>{{ book.id }}</td>
<td>{{ book.name }}</td>
<td>{{ book.author }}</td>
<td>
<img :src="'data:image/png;base64,' + photos[book.id]" />
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
books: [],
photos: {},
};
},
created() {
this.getBooks();
},
methods: {
getBooks() {
axios.get("/api/books").then((response) => {
this.books = response.data;
this.getPhotos();
});
},
getPhotos() {
this.books.forEach((book) => {
axios
.get(`/api/books/${book.id}/photo`, { responseType: "blob" })
.then((response) => {
const reader = new FileReader();
reader.readAsDataURL(response.data);
reader.onload = () => {
this.photos[book.id] = reader.result.split(",")[1];
};
});
});
},
},
};
</script>
```
以上就是Spring Boot + Vue.js + MyBatis-Plus实现以表格形式显示书籍ID对应的照片的代码实现。需要注意的是,在获取照片时需要指定响应类型为blob,然后使用FileReader将blob转换成Base64编码的字符串。
阅读全文