[英]Downloading files in Mojolicious
简单的问题。 我在我的mojolicious应用程序中生成了一个.doc文件。 我想下载它。 这是我的问题,如何让浏览器下载它?
我正在使用CPAN模块MsOffice :: Word :: HTML :: Writer来生成doc。
这是我的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 :: 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");
}
这在服务器端确实不是问题,而是在不使用(相对较新的)File API的情况下无法保存来自ajax请求的响应。 我建议用临时形式替换ajax:
$('<form method="post" action="/down_doc">')
.append(
$('<input type="hidden" name="data">')
.attr("value", JSON.stringify(data))
)
.appendTo('body')
.submit();
提交表单并且/ down_doc处理程序使用相应的content-disposition标头和文档数据进行回复时,浏览器将执行处理文件保存的工作。
如果您不打算在请求后使用服务器上的文件,则可以删除此行:
my $save = $doc->save_as("/docs/file.doc");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.