要通过Spring Boot从数据库提供图像并在HTML中显示,你需要完成以下几个步骤:
假设你有一个名为images
的表,包含以下字段:
id
(主键)name
(图片名称)data
(图片的二进制数据)src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── imageapp
│ │ ├── ImageAppApplication.java
│ │ ├── controller
│ │ │ └── ImageController.java
│ │ ├── model
│ │ │ └── Image.java
│ │ └── repository
│ │ └── ImageRepository.java
│ └── resources
│ └── static
│ └── index.html
└── test
└── java
└── com
└── example
└── imageapp
└── ImageAppApplicationTests.java
package com.example.imageapp.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private byte[] data;
// Getters and Setters
}
package com.example.imageapp.repository;
import com.example.imageapp.model.Image;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ImageRepository extends JpaRepository<Image, Long> {
}
package com.example.imageapp.controller;
import com.example.imageapp.model.Image;
import com.example.imageapp.repository.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/images")
public class ImageController {
@Autowired
private ImageRepository imageRepository;
@GetMapping("/{id}")
public ResponseEntity<Resource> getImage(@PathVariable Long id) {
Optional<Image> image = imageRepository.findById(id);
if (image.isPresent()) {
ByteArrayResource resource = new ByteArrayResource(image.get().getData());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + image.get().getName() + "\"")
.contentType(MediaType.IMAGE_JPEG)
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image App</title>
</head>
<body>
<h1>Images</h1>
<img src="/images/1" alt="Image 1">
</body>
</html>
src
路径是否正确,并确保控制器能够正确处理请求并返回图像数据。通过以上步骤,你可以实现从数据库中读取图像并在HTML页面中显示的功能。