Play Framework - only getting file content from Ok.sendFile(file) - scala

My users need to download a file when hitting a certain controller in my Play application. I thought this would do the trick:
def downloadFile = Action {
Ok.sendFile(new File("example.zip"))
}
But it seems to only give the actual content of the file instead of downloading the file. Could anybody tell me what I'm doing wrong?
Thanks

Try this instead:
def index = Action {
Ok.sendFile(
content = new java.io.File("/tmp/fileToServe.pdf"),
fileName = _ => "termsOfService.pdf"
)
}
Its from the documentation itself.
Now you don’t have to specify a file name since the web browser will
not try to download it, but will just display the file content in the
web browser window. This is useful for content types supported
natively by the web browser, such as text, HTML or images.
See this: https://www.playframework.com/documentation/2.0/ScalaStream

Turns out the REST client we are using is automatically converting the file straight into its content instead of letting us download the file. Hitting it from a normal browser works as intended.

Related

Why does the TinyMCE server-side handler example in PHP include a file extension check if you can't select a non-image anyway?

Interesting.
I wanted to add logic to catch the upload of non-images. In the PHP example in the docs, they had this:
// Verify extension
if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
header("HTTP/1.1 400 Invalid extension.");
return;
}
So I added something like that to my server's backside server-side JavaScript.
But it turned out not to be necessary. The image upload dialogs (either browse or drag-and-drop) somehow don't let you select anything but images.
If that's so, why does the example add that to the handler?
There are a couple of reasons but I'll stick to the main 2:
You may not want to accept all image types, perhaps you don't want users to upload .gif files because it will be ugly to see gif images in content, or perhaps your server doesn't support this type of image.
Using terminal commands like curl or GUI applications like Postman, you can skip the normal browser upload workflow and upload whatever you like to the server. Highly dangerous as users could upload anything if you don't perform some sort of validation, they could upload a .php file for example and cause all sorts of havoc.

Scala - Play downloads .html file instead of being opening it

I want to open an HTML file in the browser. All documentation/answers online suggest that the following is what I should have in my routes file:
GET /test controllers.Assets.at(path="/public/html", file="test.html")
Where test.html is located in public/html. However, when I go to /test, test.html is downloaded when I want it to just open in the browser (which I think is the expected behaviour of the .at function).
This has only started happening recently and no changes have been made to routes file or html file.
Any idea what might be causing this?
To serve an HTML file, you should have a Result. Results are defined within the controllers. For example:
def example = Action {OK(views.html.myhtml)}
Looks for the file myhtml.scala.html within the views folder. And here the controller method serves the result ok (http status 200) with that html file.
The asset folder is for ... well asset files which then can be used within the webpages: javascript/css/image files.

Applying transformation on html string inside a json response of ajax in moovweb

Hi I am new on moovweb and I got stuck on a requirement to apply transformation logic on ajax response which is coming in a json format containing html, which I have to add on my page.
A sample response
{
"success":true,
"html" :"<div>This can be a big html data</div>"
}
SO basically, I need to apply transformation on that html string. I gone through docs but I did't got anything to handle this kind of scenario.
Is there any way to do it?
If I understand your question correctly then there are several steps that you need to take in order to solve this issue.
Open your Moovweb project using Google Chrome, right click your mouse and choose Inspect Element which will open your Chrome Dev Tools.
Choose the Network Tab at the top of your Chrome Dev Tools which will be the second tab from the left.
Trigger the ajax call on your site and you will see under the Network Tab the response URL of the ajax call. Most of the time it will be in a format like www.yoursite.com/ajax/rest_of_url
Once you have found the ajax response URL then open your main.ts file in your tritium script and insert the following code if your response URL is similar to the format provided above:
match($path){
with(/ajax/){ #or wherever the site files for the ajax response are contained
log("--> importing ajax.ts")
#import ajax.ts
}
}
Now created a file in for your tritium code called ajax.ts. The file will be in the same location as your html.ts and main.ts files. With the code applied above to your main.ts, every time a URL is called that contains /ajax/ then the ajax.ts file will be applied.
Now you can open your new ajax.ts file that you created and start applying your tritium functions to transform the json format containing html to way you need it.

PDF.js with GWT application does not work

We have an application built on GWT framework where we want to display a PDF file without any browser plugin and are currently evaluating PDF.js to do that.
The problem is, no matter what I do, I am not able to render a PDF file onto a canvas in our GWT application. Do give some background
The PDF file ticket is retrieved from server.
The PDF.js file ticket is retrieved from server and is embedded in the HTML body by using this script
var head= document.getElementsByTagName('body')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.setAttribute('charset', 'UTF-8');
script.src=url;
head.appendChild(script);
Canvas element is created in the View (using googles MVP pattern here) and a JSNI call is made to the script which embeds the PDF.js in the HTML body using the above function. The script then makes a call to function which works with PDFJS class defined in PDF.js file.
The function to render the PDF file on canvas is as below :
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(function getPdfHelloWorld(pdf)
{
pdf.getPage(1).then(function getPageHelloWorld(page)
{
var scale = 1.25;
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({canvasContext: context, viewport: viewport});
page.startRendering(context);
alert("Finished rendering");
});
});
The canvas and context are created in the View class and passed to the javascript.
The problem here is, after the call to JSNI is made, I show alerts of all variables. The browser shows alerts except when I make a call alert(PDFJS). This shows that PDFJS variable is not being recognised in the script.
This makes me think PDF.js file is not correctly embedded in the view or there is something else that I am missing.
Note: I have downloaded most of the examples over the net and most of them work locally i.e. I can modify the PDF.js file path to pick up a local copy and the HTML still renders the PDF. It has no problem reading the PDFJS variable. Its only in this GWT application that I see these problems.
Does anyone have any clue whats happening. Your help will be highly appreciated.
Thanks
Your problem is that you're injecting the script so it aloads asynchronously, but you don't wait until after it's loaded to start using it.
Try using ScriptInjector.FromUrl to inject the script and put the rest of your code in the Callback's onSuccess.
Injecting the script synchronously (by adding it to your HTML host page, or GWT Module descriptor —note: won't work with the xsiframe linker—), as proposed by Ilya is of course also a solution.
Try to add <script src="PDF.js"/> in your .gwt.xml file and put PDF.js file in your public director

How can I simply add a downloadable PDF file to my page?

I want to add a pdf and word format of my resume to my portfolio page and make it downloadable. Does anyone have some simple script?
Add a link to the file and let the browser handle the download.
You may be over-complicating the problem. It's possible to use a href pointing to the location of the .pdf or .doc file, when a user clicks on this in their browser, generally they will be asked if they would like to save or open the file, depending on their OS/configuration.
If this is still confusing, leave a comment and I'll explain anything you don't get.
Create the PDF. Upload it. Add a link.
Save yourself 30 minutes tossing around with PDFGEN code.
You will want to issue or employ the Content-Disposition HTTP header to force the download otherwise some browsers may recognize the common file extensions and try to automatically open the file contents. It will feel more professional if the link actually downloads the file instead of launching an app - important for a resume I think.
Content-Disposition must be generated within the page from the server side as far as I know.
Option:
Upload your resume to Google Docs.
Add a link to the file on your portfolio page just as I do in the menu of my blog:
Use Google Docs Viewer passing to it the URL of the PDF as you can see in this link.