By hguser

2010-12-28 10:21:28 8 Comments

I have a Struts2 action in the server side for file downloading.

<action name="download" class="">
    <result name="success" type="stream">
        <param name="contentType">text/plain</param>
        <param name="inputName">imageStream</param>
        <param name="contentDisposition">attachment;filename={fileName}</param>
        <param name="bufferSize">1024</param>

However when I call the action using the jQuery:


in Firebug I see the data is retrieved with the Binary stream. I wonder how to open the file downloading window with which the user can save the file locally?


@John Culviner 2012-04-02 03:48:03

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a'); = 'none';
    a.href = url;
    // the filename you want = 'todo-1.json';
    alert('your file has downloaded!'); // or you know, something with better UX...
  .catch(() => alert('oh no!'));

2012 Original jQuery/iframe/Cookie based approach

Bluish is completely right about this, you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.

I created jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at my blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

Depending on what browsers you need to support you may be able to use which allows more explicit control than the IFRAME method jQuery File Download uses.

@AnthonyVO 2012-08-07 21:58:49

I love what you built but I suspect that to get more StackOverFlow credit your answer here should contain a bit more detail. Specifically on how you solved the problem.

@Pierpaolo 2013-05-15 11:59:47

can this work to force the browser to show a save dialog/ribbon for .png files as well?

@Kevin B 2013-09-23 19:47:49

it would be nice if you would mention exactly how this "plugin" gets around the limitation, rather than forcing us to go to your blog/plugin source to see it. for example, is it instead posting to an iframe? is it instead requiring the remote script to save the file and return a url to it?

@asgerhallas 2013-10-29 10:45:37

@KevinB the link in the answer explains it all

@Kevin B 2013-10-29 14:06:49

@asgerhallas Sure, but that's completely useless if said link goes away.

@Adrian 2013-10-30 13:34:01

Can I use $.fileDownload with POST instead of GET request?

@Kevin B 2013-10-30 20:10:23

I agree, a blog is a far better place to place a lengthy description of how to use your plugin and how it works. but you could have at least gave a short overview of how this plugin solves the problem. For example, this solves the problem by having the server set a cookie and having your javascript continuously look for the cookie until it exists. Once it exists, we can assume that the download is complete. With that kind of information one could easily roll their own solution very quickly, and the answer no longer relies 100% on your blog/plugin/jquery and can be applied to other libraries.

@Royi Namir 2014-01-12 08:35:04

great script , however it would've been better to check xmkHttpRequest support for file download , and then fallback to iframes.

@John Culviner 2014-01-13 16:19:12

Royi, as I understand it AJAX can never support file downloads that result in a file download popup to save to disk. Have you found a way that I'm unaware of?

@UsmanZ 2014-04-29 08:41:52

If I want to download an image from an API like:, It gets failed and gives this message: Resource interpreted as Document but transferred with MIME type image/png

@Sara N 2015-12-09 05:04:24

why I get ** $(...).html(...).dialog is not a function** error in line 85 of js? should I add sth more than the js file ?

@Royi Namir 2016-08-22 17:10:53

I don't understand : where does it says that cookie is written after the file has been downloaded. this is not a deterministic order.

@StanE 2016-09-25 19:27:50

Well... I really don't want to underrate your answer - it works - yes, but this answer and solution is overblown imho. This solution uses an iFrame - a technique that is known and used for years. Nothing special. A better answer would explain how it works and what to do: No jQuery needed. Just create an iFrame element and set .src or hidden fields and then .submit() to allow POST requests. If only a GET request with few and short params required, not even an iFrame is needed. Just change current location by window.location.href. That jQuery wrapper could be added to the answer then.

@John Culviner 2016-09-27 16:28:42

@StanE thanks for the comment. I updated the bottom of my answer which clarifies some better options now that it is 2016 (and jQuery was almost a given back when I wrote this plugin and answered this question -- which is certainly not the case anymore)

@PersyJack 2019-02-05 18:53:08

@JohnCulviner your blog link is being blocked by eset antivirus, it suggests your page contains malware so it prints "blocked by internal blacklist", just fyi

@Matthijs Wessels 2019-02-21 10:18:56

Given that Luke Madhanga's answer shows that using HTML5 you can do it using AJAX, could you edit out the "you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns)" line at the top of your answer? Your answer has so many more upvotes that it initially threw me off thinking it's still not possible. Not everyone might scroll down to read all the other answers.

@netluke 2019-05-21 15:10:41

there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.

First you need to separate the page processing from the results download.

1) Only the page calculations are made in the ajax call.

$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" },

       function(data, status) 
            if (status == "success") 
                /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */
                window.location.href = DownloadPage.php+"?ID="+29;

// For example: in the CalculusPage.php

    if ( !empty($_POST["calculusFunction"]) ) 
        $ID = $_POST["ID"];

        $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID;

// For example: in the DownloadPage.php

    $ID = $_GET["ID"];

    $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID;

    header("Content-Type: application/");
    header("Content-Disposition: inline; filename=$filename");


I hope this solution can be useful for many, as it was for me.

@Andrew Koster 2019-05-19 18:39:43


For example, you can put this line of code in a click handler:'/file.txt', '_blank');

It will open a new tab (because of the '_blank' window-name) and that tab will open the URL.

Your server-side code should also have something like this:

res.set('Content-Disposition', 'attachment; filename=file.txt');

And that way, the browser should prompt the user to save the file to disk, instead of just showing them the file. It will also automatically close the tab that it just opened.

@Eerik Sven Puudist 2019-03-29 20:26:28

I struggled with this issue for a long time. Finally an elegant external library suggested here helped me out.

@bluish 2011-10-05 11:50:29

Noone posted this @Pekka's solution... so I'll post it. It can help someone.

You don't need to do this through Ajax. Just use


@swapnesh 2013-03-01 08:49:01

Nice I was struggling with handling the download file prompt and using jquery ajax..and this solution works perfectly for me ..+1

@brichins 2013-04-24 21:45:20

Note that this requires the server to be setting a Content-Disposition header value of 'attachment', otherwise the browser will redirect to (and display) the response content

@Christopher King 2014-08-15 15:38:31

Or alternatively use<url>, '_blank'); to ensure that the download won't replace your current browser content (regardless of the Content-Disposition header).

@Yogesh Prajapati 2014-08-26 04:56:26

this is good solution but i want to show loading bar while downloading. and this is not possible with same mechanism.

@kofifus 2015-06-30 23:52:42

The problem with this solution is that if the operation fails/the server returns an error, your page will be redirected to the error page. To solve that use the iFrame solution

@Matthijs Wessels 2019-02-21 10:19:44

Given that Luke Madhanga's answer shows that using HTML5 you can do it using AJAX, could you edit out the "you can't" line in your answer? Your answer has so many more upvotes that it initially threw me off thinking it's still not possible. Not everyone might scroll down to read all the other answers.

@besil 2019-03-22 12:24:51

what if I need a custom header?

@Atomosk 2019-05-28 03:45:31

The real problem with this solution - question is about POST request.

@Aman Srivastava 2018-05-28 06:24:55

It is certain that you can not do it through Ajax call.

However, there is a workaround.

Steps :

If you are using form.submit() for downloading the file, what you can do is :

  1. Create an ajax call from client to server and store the file stream inside the session.
  2. Upon "success" being returned from server, call your form.submit() to just stream the file stream stored in the session.

This is helpful in case when you want to decide whether or not file needs to be downloaded after making form.submit(), eg: there can be a case where on form.submit(), an exception occurs on the server side and instead of crashing, you might need to show a custom message on the client side, in such case this implementation might help.

@Kit Ramos 2018-01-23 01:10:47

I found a fix that while it's not actually using ajax it does allow you to use a javascript call to request the download and then get a callback when the download actually starts. I found this helpful if the link runs a server side script that takes a little bit to compose the file before sending it. so you can alert them that it's processing, and then when it does finally send the file remove that processing notification. which is why I wanted to try to load the file via ajax to begin with so that I could have an event happen when the file is requested and another when it actually starts downloading.

the js on the front page

function expdone()
function expgo()

the iframe

<div id="exportdiv" style="display:none;">
<img src="loader.gif"><br><h1>Generating Report</h1>
<iframe id="exportif" src="" style="width: 1px;height: 1px; border:0px;"></iframe>

then the other file:

<!DOCTYPE html>
function expdone()
<iframe id="exportif" src="<?php echo "".$_GET["arguments"]; ?>"></iframe>
<script>document.getElementById('exportif').onload= expdone;</script>

I think there's a way to read get data using js so then no php would be needed. but I don't know it off hand and the server I'm using supports php so this works for me. thought I'd share it in case it helps anyone.

@manukyanv07 2015-06-28 19:06:11

Here is what I did, pure javascript and html. Did not test it but this should work in all browsers.

Javascript Function

var iframe = document.createElement('iframe'); = "IFRAMEID"; = 'none';
iframe.src = 'SERVERURL'+'?' + $.param($scope.filtro);
iframe.addEventListener("load", function () {
     console.log("FILE LOAD DONE.. Download should start now");

Using just components that is supported in all browsers no additional libraries.

enter image description here enter image description here

Here is my server side JAVA Spring controller code.

@RequestMapping(value = "/rootto/my/xlsx", method = RequestMethod.GET)
public void downloadExcelFile(@RequestParam(value = "param1", required = false) String param1,
    HttpServletRequest request, HttpServletResponse response)
            throws ParseException {

    Workbook wb = service.getWorkbook(param1);
    if (wb != null) {
        try {
            String fileName = "myfile_" + sdf.format(new Date());
            response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
        } catch (IOException e) {

@kofifus 2015-06-30 06:33:08

it seems your load event is not called for Content-disposition attachment content (because nothing is loaded into the iframe), if it works for you (you get the console.log) pls post a sample

@manukyanv07 2015-06-30 19:13:53

Here is a quick fiddle this fires the load event ass soon as the pdf file is loaded into the iframe.. this fiddle does not download becaus the key for downloading is in the server side "response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");"

@kofifus 2015-06-30 23:38:15

yes it will work in that case, but if the file is downloaded, that is the server sends Content-Disposition: attachment, then the load event will not fire which was my point

@manukyanv07 2015-07-02 21:45:50

You are totally right load event is fired right after the server is done processing starts sending the file. This is what i was looking for, 1- block the button and show processing so that the user can have a feedback that things are happening. 2 - Then when the server is done processing and about to send the file 3- (load event is fired) where I unlock the button and remove processing spinner 4 - the user is now poped up with save file or the browser starts download it in the defined download location. Sorry my English.

@aarkerio 2017-05-31 19:07:52

In Rails, I do it this way:

function download_file(file_id) {
  let url       = '/files/' + file_id + '/download_file';
    type: 'GET',
    url: url,
    processData: false,
    success: function (data) {
       window.location = url;
    error: function (xhr) {
     console.log(' Error:  >>>> ' + JSON.stringify(xhr));

The trick is the window.location part. The controller's method looks like:

# GET /files/{:id}/download_file/
def download_file
          :disposition => 'attachment',
          :url_based_filename => false)

@coderhs 2018-06-04 06:23:45

Quick question, won't this generate the file twice? Once You send the ajax request. Then you make the page redirect to the same URL as well. How can we eliminate that?

@aarkerio 2018-06-04 15:31:33

Not in my case. I only tested it on Chrome though.

@Sven 2018-06-15 10:29:23

As coderhs already states correctly, the action gets called twice.

@João Marcos 2017-03-16 09:42:37

The simple way to make the browser downloads a file is to make the request like that:

 function downloadFile(urlToSend) {
     var req = new XMLHttpRequest();"GET", urlToSend, true);
     req.responseType = "blob";
     req.onload = function (event) {
         var blob = req.response;
         var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
         var link=document.createElement('a');


This opens the browser download pop up.

@fabio.sang 2017-10-03 07:22:49

Thank you, I used this solution. Worked like a charm. Also, if you don't get a blob from the response, just create a new Blob.

@startsWith_R 2018-06-07 08:03:16

A better version with IE handling link

@Naren Yellavula 2016-08-09 12:44:30

I faced the same issue and successfully solved it. My use-case is this.

"Post JSON data to the server and receive an excel file. That excel file is created by the server and returned as a response to the client. Download that response as a file with custom name in browser"

$("#my-button").on("click", function(){

// Data to post
data = {
    ids: [1, 2, 3, 4, 5]

// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    var a;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        // Trick for making downloadable link
        a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhttp.response);
        // Give filename you wish to download = "test-file.xls"; = 'none';
// Post data to URL which handles post request"POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';

The above snippet is just doing following

  • Posting an array as JSON to the server using XMLHttpRequest.
  • After fetching content as a blob(binary), we are creating a downloadable URL and attaching it to invisible "a" link then clicking it. I did a POST request here. Instead, you can go for a simple GET too. We cannot download the file through Ajax, must use XMLHttpRequest.

Here we need to carefully set few things on the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you use other programming languages.

# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type. You can use this technique to download any kind of files.

@Tsahi Asher 2018-10-04 06:49:48

"We cannot download the file through Ajax, must use XMLHttpRequest". XMLHttpRequest is AJAX by definition. Otherwise great solution for modern web browsers. For IE, which doesn't support, I'm thinking of combining it with the proprietary msSaveOrOpenBlob method.

@EL missaoui habib 2016-04-12 16:07:24

function downloadURI(uri, name) 
    var link = document.createElement("a"); = name;
    link.href = uri;;

@Wai Ha Lee 2016-04-12 16:34:46

Could you explain your answer? That'd help others understand what you've done so they could apply your techniques to their situations.

@Yangshun Tay 2016-05-16 09:21:28

Just a warning: Safari and IE does not support the download attribute, so your file will end up having the name "Unknown"

@dario nascimento 2015-05-14 21:31:50

Adding some more things to above answer for downloading a file

Below is some java spring code which generates byte Array

@RequestMapping(value = "/downloadReport", method = { RequestMethod.POST })
    public ResponseEntity<byte[]> downloadReport(
            @RequestBody final SomeObejct obj, HttpServletResponse response) throws Exception {

        OutputStream out = new ByteArrayOutputStream();
        // write something to output stream
        HttpHeaders respHeaders = new HttpHeaders();
        respHeaders.add("X-File-Name", name);
        ByteArrayOutputStream bos = (ByteArrayOutputStream) out;
        return new ResponseEntity<byte[]>(bos.toByteArray(), respHeaders, HttpStatus.CREATED);

Now in javascript code using FileSaver.js ,can download a file with below code

var json=angular.toJson("somejsobject");
var url=apiEndPoint+'some url';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 201) {
        var res = this.response;
        var fileName=this.getResponseHeader('X-File-Name');
        var data = new Blob([res]);
        saveAs(data, fileName); //this from FileSaver.js
}'POST', url);
xhr.setRequestHeader('Authorization','Bearer ' + token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';

The above will download file

@Alireza Fattahi 2015-05-11 07:46:29

If you want to use jQuery File Download , please note this for IE. You need to reset the response or it will not download

    //The IE will only work if you reset response
    //The jquery.fileDownload needs a cookie be set
    getServletResponse().setHeader("Set-Cookie", "fileDownload=true; path=/");
    //Do the reset of your action create InputStream and return

Your action can implement ServletResponseAware to access getServletResponse()

@Luke Madhanga 2015-04-29 09:03:45

You can with HTML5

NB: The file data returned MUST be base64 encoded because you cannot JSON encode binary data

In my AJAX response I have a data structure that looks like this:

    result: 'OK',
    download: {
        mimetype: string(mimetype in the form 'major/minor'),
        filename: string(the name of the file to download),
        data: base64(the binary data as base64 to download)

That means that I can do the following to save a file via AJAX

var a = document.createElement('a');
if (window.URL && window.Blob && ('download' in a) && window.atob) {
    // Do it the HTML5 compliant way
    var blob = base64ToBlob(,;
    var url = window.URL.createObjectURL(blob);
    a.href = url; =;;

The function base64ToBlob was taken from here and must be used in compliance with this function

function base64ToBlob(base64, mimetype, slicesize) {
    if (!window.atob || !window.Uint8Array) {
        // The current browser doesn't have the atob function. Cannot continue
        return null;
    mimetype = mimetype || '';
    slicesize = slicesize || 512;
    var bytechars = atob(base64);
    var bytearrays = [];
    for (var offset = 0; offset < bytechars.length; offset += slicesize) {
        var slice = bytechars.slice(offset, offset + slicesize);
        var bytenums = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            bytenums[i] = slice.charCodeAt(i);
        var bytearray = new Uint8Array(bytenums);
        bytearrays[bytearrays.length] = bytearray;
    return new Blob(bytearrays, {type: mimetype});

This is good if your server is dumping filedata to be saved. However, I've not quite worked out how one would implement a HTML4 fallback

@notmrkyle 2017-11-14 18:34:51

The does not seem to work in firefox... Any idea?

@notmrkyle 2017-11-14 21:26:54

In some browsers you might need to add the a to the dom in order for this code to work and/or remove the revokeObjectURL part: document.body.appendChild(a)

@apil.tamang 2019-03-21 19:55:12

saved my day (and possibly a job too :) ) Not a javascript expert by any measure... more java guy. However, I have no idea why a simple "createObjectURL(new Blob([atob(base64)]))" doesn't work! It simply doesn't, while all instinct says it must. grrr...

@Shayne 2014-01-19 21:52:46

Ok, based on ndpu's code heres an improved (I think) version of ajax_download;-

function ajax_download(url, data) {
    var $iframe,

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" 

        iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>";


        iframe_html +="</form></body></html>";;

Use this like this;-

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2});

The params are sent as proper post params as if coming from an input rather than as a json encoded string as per the previous example.

CAVEAT: Be wary about the potential for variable injection on those forms. There might be a safer way to encode those variables. Alternatively contemplate escaping them.

@Marek Bar 2014-10-15 13:57:08

This is working example. Thanks. Is it possible to do that without iframe but without window.location ?

@Shayne 2014-10-17 02:44:24

I suppose you could just append the hidden form to the bottom of the DOM. Also possibly worth exploring is use of the Shadow dom , although thats not necessarily well supported on older browsers.

@void 2016-01-16 10:09:45

In this code I am getting this error. Uncaught SecurityError: Blocked a frame with origin "" from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.

@bartex9 2017-01-12 09:23:57

How can I map this form to some model class? I have: @ResourceMapping() public void downloadFile(final ResourceRequest request, final ResourceResponse response, @ModelAttribute("downForm") FormModel model) but it's not working..

@Shayne 2017-01-13 02:23:46

void : That would likely be some sort of cross origin security issue. Thats probably a whole stack overflow question in and of it self. @bartex9 : That would depend heavily on what sort of framework your using. But the principle would be to take the name and path and store that, whilst pushing the file itself into a web accessible area of the file system, or something like amazon S3 for high availability

@Yannick Richard 2014-01-30 18:12:50

Ok so here is the working code when Using MVC and you are getting your file from a controller

lets say you have your byte array declare and populate, the only thing you need to do is to use the File function (using System.Web.Mvc)

byte[] bytes = .... insert your bytes in the array
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "nameoffile.exe");

and then, in the same controller, add thoses 2 functions

protected override void OnResultExecuting(ResultExecutingContext context)


    private const string FILE_DOWNLOAD_COOKIE_NAME = "fileDownload";

    /// <summary>
    /// If the current response is a FileResult (an MVC base class for files) then write a
    /// cookie to inform jquery.fileDownload that a successful file download has occured
    /// </summary>
    /// <param name="context"></param>
    private void CheckAndHandleFileResult(ResultExecutingContext context)
        if (context.Result is FileResult)
            //jquery.fileDownload uses this cookie to determine that a file download has completed successfully
            Response.SetCookie(new HttpCookie(FILE_DOWNLOAD_COOKIE_NAME, "true") { Path = "/" });
            //ensure that the cookie is removed in case someone did a file download without using jquery.fileDownload
            if (Request.Cookies[FILE_DOWNLOAD_COOKIE_NAME] != null)
                Response.Cookies[FILE_DOWNLOAD_COOKIE_NAME].Expires = DateTime.Now.AddYears(-1);

and then you will be able to call your controller to download and get the "success" or "failure" callback

$.fileDownload(mvcUrl('name of the controller'), {
            httpMethod: 'POST',
            successCallback: function (url) {
            //insert success code

            failCallback: function (html, url) {
            //insert fail code

@ndpu 2014-01-16 14:11:13

I have created little function as workaround solution (inspired by @JohnCulviner plugin):

// creates iframe and form in it with hidden field,
// then submit form with provided data
// url - form url
// data - data to form field
// input_name - form hidden input name

function ajax_download(url, data, input_name) {
    var $iframe,

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" +
                  "<input type=hidden name='" + input_name + "' value='" +
                  JSON.stringify(data) +"'/></form>" +

Demo with click event:

$('#someid').on('click', function() {
    ajax_download('/download.action', {'para1': 1, 'para2': 2}, 'dataname');

@Shayne 2014-01-19 21:44:24

That sends the data in a very strange way to the server though. I wonder if it could be altered to create compliant POST?

@ndpu 2014-01-20 07:50:26

@Shayne it could, but it works ok for me with json

@Andrea Ligios 2013-06-03 15:53:04

1. Framework agnostic: Servlet downloading file as attachment

<!-- with JS -->
<a href="javascript:window.location='downloadServlet?param1=value1'">

<!-- without JS -->
<a href="downloadServlet?param1=value1" >download</a>

2. Struts2 Framework: Action downloading file as attachment

<!-- with JS -->
<a href="javascript:window.location='downloadAction.action?param1=value1'">

<!-- without JS -->
<a href="downloadAction.action?param1=value1" >download</a>

It would be better to use <s:a> tag pointing with OGNL to an URL created with <s:url> tag:

<!-- without JS, with Struts tags: THE RIGHT WAY -->    
<s:url action="downloadAction.action" var="url">
    <s:param name="param1">value1</s:param>
<s:a href="%{url}" >download</s:a>

In the above cases, you need to write the Content-Disposition header to the response, specifying that the file needs to be downloaded (attachment) and not opened by the browser (inline). You need to specify the Content Type too, and you may want to add the file name and length (to help the browser drawing a realistic progressbar).

For example, when downloading a ZIP:

                   "attachment; filename=\"name of my\"");
response.setHeader("Content-Length", myFile.length()); // or myByte[].length...

With Struts2 (unless you are using the Action as a Servlet, an hack for direct streaming, for example), you don't need to directly write anything to the response; simply using the Stream result type and configuring it in struts.xml will work: EXAMPLE

<result name="success" type="stream">
   <param name="contentType">application/zip</param>
   <param name="contentDisposition">attachment;filename="${fileName}"</param>
   <param name="contentLength">${fileLength}</param>

3. Framework agnostic (/ Struts2 framework): Servlet(/Action) opening file inside the browser

If you want to open the file inside the browser, instead of downloading it, the Content-disposition must be set to inline, but the target can't be the current window location; you must target a new window created by javascript, an <iframe> in the page, or a new window created on-the-fly with the "discussed" target="_blank":

<!-- From a parent page into an IFrame without javascript -->   
<a href="downloadServlet?param1=value1" target="iFrameName">

<!-- In a new window without javascript --> 
<a href="downloadServlet?param1=value1" target="_blank">

<!-- In a new window with javascript -->    
<a href="'downloadServlet?param1=value1');" >

@Vedran Maricevic. 2015-05-29 14:23:18

Sir, Your input: "Content-Disposition", "inline;.... saved the poor coder's day :)

@Andrew Koster 2019-05-19 18:31:44

This is the only answer that mentions "" (one of the comments mentions it).

Related Questions

Sponsored Content

26 Answered Questions

[SOLVED] Download File Using Javascript/jQuery

57 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

33 Answered Questions

[SOLVED] How can I upload files asynchronously?

23 Answered Questions

[SOLVED] jQuery Ajax File Upload

13 Answered Questions

[SOLVED] Sending multipart/formdata with jQuery.ajax

17 Answered Questions

[SOLVED] Writing files in Node.js

16 Answered Questions

[SOLVED] Handle file download from ajax post

30 Answered Questions

[SOLVED] How to avoid Java code in JSP files?

  • 2010-07-05 07:24:06
  • chmoelders
  • 270572 View
  • 1619 Score
  • 30 Answer
  • Tags:   java jsp scriptlet

12 Answered Questions

4 Answered Questions

[SOLVED] wget command to download a file and save as a different filename

  • 2013-05-21 20:01:54
  • noobcoder
  • 462581 View
  • 467 Score
  • 4 Answer
  • Tags:   download wget

Sponsored Content