Java 下载/显示存储在SQL表中的文件
我接管了一个文件上传功能中断的项目。当前,当上传文件时,它会转换为类似于so的字节数组,然后存储在SQL表中Java 下载/显示存储在SQL表中的文件,java,tapestry,Java,Tapestry,我接管了一个文件上传功能中断的项目。当前,当上传文件时,它会转换为类似于so的字节数组,然后存储在SQL表中 public static byte[] saveAttachment(String filePath) throws IOException{ InputStream inputStream = new FileInputStream(filePath); byte[] buffer = new byte[1048576]; int bytesRead;
public static byte[] saveAttachment(String filePath) throws IOException{
InputStream inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[1048576];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while((bytesRead = inputStream.read(buffer)) != -1){
output.write(buffer, 0 , bytesRead);
}
inputStream.close();
return output.toByteArray();
}
我不能说我同意已经采取的方法,但唉,我必须与之合作。我的问题是如何检索要显示的文件
我读过
并尝试(但没有成功)
但是,我不确定这是正确/最佳的解决方案 最好将文件保存到某个位置,然后将该位置保存到数据库中。这将有助于确定数据库的大小 此外,该文件是可用的,可以轻松检索,无需沉重的数据库对象 或者,您可以在数据库中添加BLOB列,并将文件存储在数据库中 将文件转换为文件对象
File image = new File("D:\\a.gif");
FileInputStream fis = new FileInputStream(image);
stmt.setBinaryStream(1, fis, (int) image.length());
添加并使用
File image = new File("D:\\java.gif");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(3);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
假设row.getBytes()以字节数组的形式返回图像,row.getName()为图像名称:
return new StreamResponse() {
@Override
public String getContentType() {
return "image/jpeg";
}
@Override
public InputStream getStream() throws IOException {
return new ByteArrayInputStream(row.getBytes());
}
@Override
public void prepareResponse(Response response) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + row.getName() + "\"");
}
};
我更喜欢这种方法,但至少目前我的手还没有准备好检查现在我修改了我的解决方案我正在使用JPA/Eclipselink。等价物是什么?您的文件作为字节数组存储在DB中,对吗?为什么将其转换为文件只是为了显示给客户端?您可以从数据库的字节数组返回InputStream。@xl0e是的,它存储为字节数组。如何向用户显示这些文件?这里的功能是查看上传的附件,可以是任何文件格式。上传部分工作正常。
return new StreamResponse() {
@Override
public String getContentType() {
return "image/jpeg";
}
@Override
public InputStream getStream() throws IOException {
return new ByteArrayInputStream(row.getBytes());
}
@Override
public void prepareResponse(Response response) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + row.getName() + "\"");
}
};