简体   繁体   中英

"download" instead of "open" a text file

In an GWT App, I would like to have a button which when clicked will download a file at a given url. It's a plain text log file (not html) with a .out suffix.

My first attempt is using "window.open()" (tried both gwt and native javascript window.open)

Unfortunately, the browser (tried chrome and firefox and ie) is trying to be smart and notices that the file is a text file, and therefore shows the content in a popup, instead of downloading it. To make matters worse, it seems that the browser is rendering the .out file as if it's html, and messes up all the line breaks and tabs (basically any white spaces).

I'm not in control of the http server that serves the .out file. So I'm looking for a client side solution.

Can someone suggest a solution for me?

Thanks.

It's not possible without modifying the headers coming from the server.

Modern browsers support the download attribute in <a> tags which allows you to trigger a download from a normal link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes

Unfortunately, IE11 is not a "modern browser" .

With html5, it is possible now. Set a "download" attr in element.

<a href="http://link/to/file" download="FileName">Download it!</a>

Source : http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

Add this header to your file.

Content-Disposition: attachment; filename=log file.out;

or use this code in the template:

<html>
  <head>
    <meta http-equiv="content-type" content="attachment; filename=log file.out">

RequestBuilder rb = super.doCreate(serviceEntryPoint);
rb.setHeader("Content-Disposition", "attachment; filename=log file.out;");
return rb;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM