用取绝对路径的方法,将图片显示在页面上,如何存取,用Spring搭建对的前后端代码,还有js代码
时间: 2024-04-21 14:23:25 浏览: 12
要将图片显示在页面上并存取,你可以使用以下步骤来实现:
1. 前端代码(HTML/CSS/JS):
在HTML页面中使用`<img>`标签来显示图片,并使用JavaScript来与后端进行交互。
```html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// 发送请求获取图片数据
$.ajax({
url: '/getImage', // 后端接口地址
method: 'GET',
success: function(data) {
// 将返回的图片数据设置为图片的src属性
$('#myImage').attr('src', 'data:image/png;base64,' + data);
}
});
});
</script>
</head>
<body>
<img id="myImage" src="" alt="Image">
</body>
</html>
```
2. 后端代码(Spring框架):
使用Spring框架来处理前端请求,读取图片文件并将其转换为Base64编码的字符串返回给前端。
```java
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.IOException;
import java.nio.file.Files;
@Controller
public class ImageController {
@GetMapping("/getImage")
public ResponseEntity<byte[]> getImage() throws IOException {
// 读取图片文件
ClassPathResource imgFile = new ClassPathResource("path/to/your/image.png");
byte[] imageBytes = Files.readAllBytes(imgFile.getFile().toPath());
// 将图片转换为Base64编码的字符串
String base64Image = java.util.Base64.getEncoder().encodeToString(imageBytes);
// 返回Base64编码的图片数据
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_PNG)
.body(base64Image.getBytes());
}
}
```
3. 调整路径:
请将上述代码中的`path/to/your/image.png`替换为图片文件的实际路径。确保图片文件位于类路径(resources目录)下或者提供正确的绝对路径。
这样,当访问前端页面时,会发送一个GET请求到后端的`/getImage`接口,后端会读取图片文件并将其以Base64编码的字符串形式返回给前端,前端接收到后端返回的数据后,将其设置为`<img>`标签的src属性,从而显示图片在页面上。