简单的问题。我的 mojolicious 应用程序中生成了一个 .doc 文件。我想下载它。这就是我的问题,如何让浏览器下载它?
我正在使用 CPAN 模块 MsOffice::Word::HTML::Writer生成文档。
这是我的 mojolicious 应用程序中的子例程,它由 Jquery 中的 Ajax 请求调用:
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
$self->res->headers->content_disposition("attachment;filename=file.doc");
$self->res->headers->content_type('application/msword');
$self->render(data => $doc->content);
}
这是我在 Jquery 中的 Ajax 请求:
var request = $.ajax({
url: "/down_doc",
type: "post",
data: {'data': data},
});
request.done(function(response, textStatus, jqXHR) {
window.location.href = response;
});
我知道我的 Ajax“完成”处理程序是错误的,我只是在试验。如何让我的网页提示保存和下载 .doc 文件?
最佳答案
你很接近,但我会推荐以下任一选项...
使用 Mojolicious 处理文件下载
可以安装插件Mojolicious::Plugin::RenderFile使这变得容易。
示例
plugin 'RenderFile';
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
$self->render_file('filepath' => "/docs/file.doc");
}
或者,如果您只想使用 Mojo
,则以下内容将起作用,并在下面的链接中进行了进一步解释。
use Cwd;
app->static->paths->[0] = getcwd;
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
shift->render_static("/docs/file.doc");
}
关于javascript - 在 Mojolicious 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713729/