我无法将我的blob转换为缓冲图像,所以我可以使用它。我从使用inputstream上传的数据库中获取blob(jpg图像)。在我的数据库中,它存储为BufferedInputStream,我注意到了。我得到的blob很好,它的一堆奇怪的符号,并说它的JPG,所以图像必须罚款。任何人都可以发现我做错了什么吗?也许我转换它错了?在image = ImageIO.read(new ByteArrayInputStream(data));图像返回null。将BufferedInputStream转换为图像
@GET
@Path("{id}")
@Produces("image/*")
public Response post(@PathParam("id") String id) throws IOException {
Connection con = connection();
Blob blob = getPhoto(con);
BufferedImage image = null;
byte[] data = null;
int blobLength = 0;
try {
blobLength = (int) blob.length();
data = blob.getBytes(1, blobLength);
image = ImageIO.read(new ByteArrayInputStream(data));
// ImageIO.write(image, "JPEG", new File("C:/Users/Nicolas/Desktop/image.jpg"));
} catch (SQLException e2) {
e2.printStackTrace();
}
return Response.ok(image).build();
}
我如何写数据库
public void postPhoto(Connection con, InputStream uploadedInputStream){
String mySQL = "INSERT INTO photos (photo) values (?)";
PreparedStatement pStmt = con.prepareStatement(mySQL);
pStmt.setBlob(1, uploadedInputStream);
pStmt.execute();
}
我如何通过验证uploadedInputStream
是一个有效的图像文件发送到我的servlet
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append("file", file);
var parameters="first="+firstName+"&last="+lastName+"&file="+file;
xmlhttp.open("post","http://localhost:8080/restService/api/submitinfo",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(formData);
数据是否填充了blob.getBytes()后面的字节? – MGorgon
是的,它是填充字节和几乎相同的字节数量的原始jpg – NightSkyCode
我会先检查文件。将'data'写入File并尝试用某个图像查看器打开它。如果你有有效的jpg文件,试着用'ImageIO.read(new File(...);'来读取它。我认为问题在于数据不是有效的图像。 – MGorgon