下载/显示存储在SQL表中的文件



我接管了一个文件上传功能坏掉的项目。目前,当文件上传时,它会像这样转换为byteArray,然后存储在SQL表中

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();
}

不能说我同意已经采取的方法,但唉,我必须使用它。我的问题变成了如何检索要显示的文件?

我读过https://wiki.apache.org/tapestry/Tapestry5HowToStreamAnExistingBinaryFile

并尝试过(没有用(

@OnEvent(component="viewAttachment")
private Object viewAttachment(){
final File getFile();
final OutputStreamResponse response = new OutputStreamResponse() {
    public String getContentType() {
        return "image/jpg"; 
    }
    public void prepareResponse(Response response) {
        response.setHeader ("Content-Disposition", "attachment; filename="" + file.getName() + """);
    }
    @Override
    public void writeToStream(OutputStream out) throws IOException {
        try {
            InputStream in = new FileInputStream(file);
            IOUtils.copy(in,out);
            in.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }                   
    }
};
return response;
}

但是,我不确定这是正确/最佳的解决方案。

假设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() + """);
        }
    };

最好将文件保存在某个位置,然后将该位置保存在数据库中。这将有助于拥有数据库的大小。

此外,文件可用,无需繁重的数据库对象即可轻松检索。

或者,您可以在数据库中添加 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(); 

最新更新