在Mojolicious中下载文件 [英] Downloading files in Mojolicious

查看:82
本文介绍了在Mojolicious中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题.我在mojolicious应用中生成了一个.doc文件.我要下载.这是我的问题,如何获取浏览器进行下载?

Simple question. I have a .doc file generated in my mojolicious app. I want to download it. That's my question, how do I get the browser to download it?

我正在使用CPAN模块 MsOffice :: Word :: HTML :: Writer 生成文档.

I'm using the CPAN module MsOffice::Word::HTML::Writer to generate the doc.

这是我的Mojolicious应用程序中的子例程,它由Jquery中的Ajax请求调用:

Here is the sub routine in my mojolicious app, it is called by an Ajax request in Jquery:

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请求:

Here is my Ajax request in Jquery:

var request = $.ajax({
  url: "/down_doc",
  type: "post",
  data: {'data': data},
});

request.done(function(response, textStatus, jqXHR) {
  window.location.href = response;
});

我知道我的Ajax完成"处理程序是错误的,我只是在做实验.如何使我的网页提示保存和下载.doc文件?

I know that my Ajax "done" handler is wrong, I was just experimenting. How do I make my webpage prompt to save and download the .doc file?

推荐答案

这在服务器端确实不是问题,但是,如果不使用(相对较新的),就无法保存来自ajax请求的响应文件API.我建议将ajax替换为临时形式:

This really isn't a problem on the server side, but rather that you can't save the response from an ajax request without using the (relatively new) File API. I would suggest replacing the ajax with a temporary form:

$('<form method="post" action="/down_doc">') 
    .append( 
       $('<input type="hidden" name="data">')
          .attr("value", JSON.stringify(data))
    )
    .appendTo('body') 
    .submit();

提交表单后,/down_doc处理程序以适当的content-disposition标头和文档数据答复时,浏览器将完成处理文件保存的工作.

When form is submitted and your /down_doc handler replies with the appropriate content-disposition header and the document data, the browser will do the work of handling the file save.

如果您不打算在请求后使用服务器上的文件,则可以删除此行:

If you're not planning to use the file on the server after the request, this line can be removed:

my $save = $doc->save_as("/docs/file.doc");

这篇关于在Mojolicious中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆