idea写一段图片存储到数据库的代码
时间: 2023-11-24 22:06:03 浏览: 82
好的,以下是使用 Spring Boot 和 MyBatis-Plus 框架实现将图片存储到数据库的代码:
1. 创建图片存储的实体类,包含图片的名称、类型、大小和二进制数据:
```java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Image {
private String name;
private String type;
private long size;
private byte[] data;
}
```
2. 创建数据库表,包含图片的名称、类型、大小和二进制数据的字段:
```sql
CREATE TABLE `image` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`size` bigint(20) DEFAULT NULL,
`data` longblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
3. 创建 Mapper 接口,定义图片的增、删、改、查操作:
```java
@Mapper
public interface ImageMapper extends BaseMapper<Image> {
}
```
4. 创建 Service 层,实现图片的增、删、改、查操作:
```java
@Service
public class ImageService {
@Autowired
private ImageMapper imageMapper;
public void saveImage(Image image) {
imageMapper.insert(image);
}
public void deleteImageById(Long id) {
imageMapper.deleteById(id);
}
public void updateImage(Image image) {
imageMapper.updateById(image);
}
public Image getImageById(Long id) {
return imageMapper.selectById(id);
}
public List<Image> getAllImages() {
return imageMapper.selectList(null);
}
}
```
5. 创建 Controller 层,处理图片上传和下载请求:
```java
@RestController
@RequestMapping("/images")
public class ImageController {
@Autowired
private ImageService imageService;
@PostMapping
public void uploadImage(@RequestParam MultipartFile file) throws IOException {
Image image = new Image();
image.setName(file.getOriginalFilename());
image.setType(file.getContentType());
image.setSize(file.getSize());
image.setData(file.getBytes());
imageService.saveImage(image);
}
@GetMapping("/{id}")
public ResponseEntity<byte[]> downloadImage(@PathVariable Long id) {
Image image = imageService.getImageById(id);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(image.getType()));
headers.setContentLength(image.getSize());
headers.setContentDisposition(ContentDisposition.builder("attachment").filename(image.getName()).build());
return new ResponseEntity<>(image.getData(), headers, HttpStatus.OK);
}
}
```
6. 编写前端页面,实现图片上传和下载功能。
以上就是将图片存储到数据库的代码示例,希望对您有所帮助!
阅读全文