Java 如何在给定的MySQL DB代码中保存图像
我正试图在数据库中保存一个文件 这是我的密码Java 如何在给定的MySQL DB代码中保存图像,java,mysql,image,spring-mvc,Java,Mysql,Image,Spring Mvc,我正试图在数据库中保存一个文件 这是我的密码 public class DocumentForm { @NotNull @Size(min = 1) private byte[] file; public byte[] getFile() { return file; } public void setFile(byte[] file) { this.file = file; } ... } 控制器
public class DocumentForm {
@NotNull
@Size(min = 1)
private byte[] file;
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
...
}
控制器
@RequestMapping(value = "document", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute DocumentForm documentForm, Errors errors, RedirectAttributes ra) {
if (errors.hasErrors()) {
return "document/document";
}
Document d = projectRepository.save(documentForm.createDoc());
MessageHelper.addSuccessAttribute(ra, "document.success");
return "redirect:/";
}
看法
在数据库中:
它显示图像被保存为BLOB
然而,当我试图查看图像时,通过在mySQL浏览器中单击编辑器中的Open Value,我看到的只是图像文件的名称
如何在MySQL数据库中保存图像?如何检索它并显示在我的视图中您可以通过使用可以保存表单数据的Part类来执行此操作 Part filePart=request.getPartimage inputStream=filePart.getInputStream
语句1,inputStream blob类型是一个二进制字段,包含任何二进制数据的内容。因为MySql浏览器可能不知道blob的类型,所以它只能提供名称。数据,应该都还在那里 也就是说,我想您会发现,通常图像不存储在数据库中,而是存储对磁盘上图像的引用。这是因为数据库对于大型二进制存储不是很有效 您可能希望存储在数据库中以适当引用图像的内容: 图像的名称 图像数据的大小 也许是尺寸 指示服务器将从何处返回的规范url。 如果您发现自己需要通过servlet容器tomcat、jboss、w/e来流式传输图像,那么您可以通过创建流式html响应来实现。类似于此,其中InputStream是指向blob二进制数据的流:
public void serveInputStreamByResponse(HttpServletResponse response, InputStream in) {
try {
FileCopyUtils.copy(in, response.getOutputStream());
} catch (IOException e) {
// do something
} finally {
if (in != null) {
try {
in.close(); // very important
} catch (IOException e) {
// do something
}
}
}
}
您的建议是将映像保存在驱动器中,并将引用保存在数据库中?是的。您会发现这样做效率更高,因为您可以将图像的服务卸载到服务器apache、nginx等,而不是让servlet容器来处理它。另外,仅仅从数据库中读取图像不是很有效。
public void serveInputStreamByResponse(HttpServletResponse response, InputStream in) {
try {
FileCopyUtils.copy(in, response.getOutputStream());
} catch (IOException e) {
// do something
} finally {
if (in != null) {
try {
in.close(); // very important
} catch (IOException e) {
// do something
}
}
}
}