为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3242003 2023-01-05 17:17:14
我以 String 格式编码了一个文件名,并存储在一个表列文件中。现在用另一种方法我想将该文件下载到特定的本地路径。所以我正在解码保存在该路径中的文件,正在创建文件但文件中的内容丢失,这意味着正在创建空文件。could you please help me to overcome this issuetry{        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 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

最常见的文件存储方式是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());

       }

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


更新:


为了将文件转换为 bytes[]:


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

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


查看完整回答
反对 回复 2023-01-05
  • 1 回答
  • 0 关注
  • 103 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信