Perl,GridFS和存储/恢复.docx文件



我正在使用perl和MongoDB::GridFS(以及其他mongo模块)来存储和检索文件。它适用于.txt,但我想存储和检索.docx。这是我的代码:

#!usr/bin/perl
use MongoDB::GridFS;
use MongoDB;
use MongoDB::Database;
use MongoDB::OID;
my $conn = new MongoDB::Connection; 
my $db   = $conn->test; #name of our local db is test...default of mongoDB
my $coll = $db->err0; #err0 is the name of the collection
my $grid = $db->get_gridfs;
my $fh = IO::File->new("wordtoyamutha.docx", "r");
$grid->insert($fh, {"filename" => "test"});
my $outfile = IO::File->new("wordtoyamutha.docx", "w");
my $file = $grid->find_one({"filename" => "test"});;
$file->print($outfile);

我首先创建了一个名为"wordtoyamutha.docx"的.docx,然后运行上面的代码,最后三行被注释掉。它运行良好,我的MongoDB fs.files中出现了一个新条目。然后我删除了运行代码.docx所有"存储"代码都被注释掉了 - 明确地说,这些行是从上面注释掉的:

my $fh = IO::File->new("wordtoyamutha.docx", "r");
$grid->insert($fh, {"filename" => "test"});

出现了一个标题为wordtoyamutha的文档...但是当我尝试打开它时,Word抱怨它因损坏而变得不可读。

我不知道任何其他方法来检索文件...这就是Perl MongoDB::GridFS建议做的所有事情......这有什么诀窍?

来自 Word 的确切错误出现在 dailog 中,并显示"由于内容有问题,无法打开文件 wordtoyamutha"。

以下是我得到的帮助的结果(功能齐全!):

#!usr/bin/perl
#Using Strawberry Perl and on Windows 7 box
use strict;
use warnings;
use MongoDB::GridFS;
use MongoDB;
use MongoDB::Database;
use MongoDB::OID;
my $conn = new MongoDB::Connection; 
my $db   = $conn->test; #name of our local db is test...default of mongoDB
my $grid = $db->get_gridfs;
my $fh = IO::File->new("cool.docx", "r");
$fh->binmode();
$grid->insert($fh, {"filename" => "docx"});
my $outfile = IO::File->new("return.docx", "w");
$outfile->binmode();
my $file = $grid->find_one({"filename" => "docx"});
$file->print($outfile);

同样,这不是一个很棒的脚本 - 这里的东西是硬编码的。这会从与perl脚本相同的目录中提取一个名为"cool"的docx文件,将其存储在我的db"test"中,然后在与perl脚本相同的目录中再次检索它作为return.docx。AKA 返回.docx将出现在目录中并成为精确副本!这本身并不是很有用 - 但显然,如果我们能做到这一点,这意味着我们可以做得更多。

======

=我需要更改什么才能使此脚本适合我?===

=====

参数名称"docx"是可变的 - 它是在 GridFS 数据库中对文件的寻址方式。那么显然文件名是可更改的。未来的用户可能还必须将"我的$db"行更改为

my $db   = $conn->name_of_your_DB; 

如果您不知道数据库的名称是什么,请进入 Mongo shell,键入

show dbs

它给出了一个数据库列表。现在选择列出的数据库之一 - 我们称之为db_you_want_to_use。现在键入

use db_you_want_to_use

并更改脚本中的$db行以指向您刚刚键入的相同内容,即:

my $db   = $conn->db_you_want_to_use; 

使用 GridFS 插入文件后,它会创建一个名为 fs.files 的集合。用

db.fs.files.find()

查看数据库中的条目 - AKA 以检查内容是否正确插入。

最新更新