Uploading files to Mojolicious
Simple question. I have a .doc file generated in my modjolized application. I want to download it. What's my question, how can I load his browser?
I am using CPAN module MsOffice :: Word :: HTML :: Writer to create a document.
Here is a subroutine in my modjolic application, it is called on 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);
}
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;
});
I know my Ajax "done" handler is wrong, I was just experimenting. How do I get my webpage to ask to save and load a .doc file?
source to share
This is really not a server side issue, but rather that you cannot save the response from an ajax request without using the (relatively new) File API. I would suggest replacing 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();
When the form is submitted and your / down_doc handler responds with the appropriate content header and document data, the browser will do the job of saving the file.
If you do not plan to use the file on the server after the request, this line can be removed:
my $save = $doc->save_as("/docs/file.doc");
source to share
You where are pretty close, but I would recommend one of the following options ...
Uploading a file with Mojolicious
You can install the Mojolicious :: Plugin :: RenderFile plugin to do this easily.
Example
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");
}
Or, if you only want to use Mojo
, the following will work: further explained in the link below.
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");
}
source to share