springboot+js实现图片预览,图片以blob类型存入数据库中
【代码】springboot+js实现图片预览,图片以blob类型存入数据库中。
·
实体类:
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import javax.persistence.Lob;
import java.sql.Blob;
@TableName("PBMS_CQRJL")
@Data
public class PbmsCqrjlBean {
/**
* id
*/
private String id;
/**
* 虫情图片
*/
@Lob //此注解会将blob类型数据映射为byte[]类型
private byte[] image;
}
controller层:
@GetMapping("/keepView")
public ResponseEntity<String> keepView(@RequestParam("id") String id) throws IOException, SQLException {
//假设这是你从服务层获得到的图片byte[]
byte[] imageData = cqInfoService.keepView(id);
if (imageData == null) {
return ResponseEntity.notFound().build();
}
String base64String = Base64.getEncoder().encodeToString(imageData);
return ResponseEntity.ok()
.contentType(MediaType.TEXT_PLAIN) // 根据BLOB数据的实际类型选择合适的MIME类型
.body(base64String);
}
html:
<img id="img-url" src="" style="width: 100%;"/>
js文件:
//数据交互可自行选择,例如axios
$.ajax({
url: "/web_cq/keepView",
type: "GET",
data: {id:element.dataset.image},
success: function (response) {
console.log("回调结果",response);
// 将Base64字符串解码为二进制数据
const binaryString = atob(response);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const blob = URL.createObjectURL(
new Blob([bytes], {type: 'image/png'})
);
const imagePreview = document.getElementById('img-url');
imagePreview.src = blob;
},
error: function () {
openErrorView("操作失败,请重试!");
}
});
更多推荐
已为社区贡献1条内容
所有评论(0)