通过解码文件的编码字符串格式从数据库下载文件

时间:2019-06-06 05:33:18

标签: java spring

  

我将文件名编码为String格式并存储在表列中   文件。现在,我想用另一种方法将该文件下载到   特定的本地路径。所以我正在解码文件以将其保存在其中   路径,正在创建文件,但是文件中的内容丢失,   表示正在创建空文件。

could you please help me to overcome this issue

try{
        session=getSession();
        ProjectsDO project = em.find(ProjectsDO.class, id);
          //got the encode file from db
        String encodedFile=project.getProjectFile();

//  decoding the file to actual file
        byte[] decodedBytes = Base64.getDecoder().decode(encodedFile);
        String decodedString = new String(decodedBytes);

//saving the file to required path
         FileOutputStream fout=new FileOutputStream("C:/Users/veerraju/Desktop/sap/projects/"+decodedString
); 
           System.out.println("file created succefully");
        }catch(Exception e){
            System.out.println(e.getMessage());
        }


//this is the method used to encode only file name(that means it encodes"quote.jpg".
String originalInput = "C:/Users/veerraju/Desktop/sap/quote.jpg"; //cXVvdGUuanBn
    File file=new File(originalInput);
    String fileName=file.getName();
        String encodedFile = Base64.getEncoder().encodeToString(fileName.getBytes());

1 个答案:

答案 0 :(得分:2)

最常见的文件存储方式是byte [],Clob,Blob。您已经创建了FileOutputStream来写入文件内容,但是没有在其中填充数据。因此,您可能在以下两种情况之一中失败了:

  • 您仅将文件名保留在数据库中,如果这样,则文件从一开始就为空
  • 您已按照路径中的内容使用内容,为输出文件创建了无效路径,请首先记录该路径,该路径是否正确。

因此,假设您拥有此模型:

class ProjectsDO {

    private String fileName;
    private byte[] fileContent;
    // getters and setters
}

您的方法将如下所示:

    try{
        session = getSession();
        ProjectsDO project = em.find(ProjectsDO.class, id);
        // read the file name or the full path
        String fileName=project.getFileName();

        // read the content of the file
        byte[] fileContent = project.getFileContent();

       //compute the output file path (combine directory and file name)
       Path path = Paths.get("C:/Users/veerraju/Desktop/sap/projects/"+fileName);
       // this path was missing - fill the file with content
       Files.write(path,fileContent);
         System.out.println("file created succefully");
       } catch(IOException e){
         System.out.println(e.getMessage());
       }

您当然可以对文件内容进行编码,但是为了简化此任务,我跳过了这一部分。

更新:

为了将文件转换为字节[]:

   byte[] fileContent = Files.readAllBytes(file.toPath());

如果您的数据库不支持byte []列类型,那么您将需要将其持久保存为varchar / text列,但性能会更差。