1

I want to download a text file (ex:-somthing.txt). When I use an ancor tag , the file is downloaded, but i want to download the file using an ajax call.

HTML code:

<body>
    <a href="#" id="exportViewRule">Export</a>
</body>

JavaScript code :

$("#exportViewRule").click(function(){
            $.ajax({
                url : "/download/myDir/exportFile",
                type : "GET",
                contentType : "text/plain",             
                success : function(data){
                    alert(data);
                }

        });
    });

java code:

@Path("/myDir")
public class IdnsDataHandler {

@GET
    @Path("/exportFile")
    @Produces("text/plain")
    public Response exportFile(){
        File file=new File("/home/cerdik/Desktop/some.text");
        ResponseBuilder response=Response.ok((Object)file);
        response.header("Content-Disposition","attachment; filename=export-file.text");
        return response.build();
    }
}

When i use this code bellow (without javascript), the download works.

HTML code:

<body>
    <a href="./download/myDir/exportFile" id="exportViewRule">Export</a>
</body>
Mouser
  • 13,132
  • 3
  • 28
  • 54
Vasantha Raj
  • 637
  • 1
  • 6
  • 22
  • There is no '.' in the `url` of your jquery call. There is one in the code that works. – dotvav Aug 10 '15 at 08:23
  • Also do you have browser logs or server logs that would tell us the status of the http requests? – dotvav Aug 10 '15 at 08:25
  • http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – Stefan Aug 10 '15 at 08:33
  • may i use '.' that query always working wrong sir – Vasantha Raj Aug 10 '15 at 08:34
  • Why do you want to use a AJAX request instead of a download link? – Mouser Aug 10 '15 at 09:12
  • @Mouser , i wont use some.txt file only, some time i use another files( ex: some1.txt, some2.txt... etc), so only. when i click id=exportViewRule, that time i pass some keys and that type of file i want to execute. so only sir – Vasantha Raj Aug 10 '15 at 09:20
  • A link allows querystrings, they are sent as `GET`. So if you provide a download link like this: `./download/myDir/exportFile?no=1`, you can let your server side script download the correct file. – Mouser Aug 10 '15 at 09:27

5 Answers5

2

Thanks to all, and i found another solution for this type of downloading method, now i did not use ajax call, below shows to my success code

Html:

<a id="exportView" style="cursor:pointer">Export</a>

javaScript:

$("#exportView").click(function(){
            var exportId = $('#serviceRules option:selected').attr("stream");
            var TakeHref="./download/myDir/exportFile"+exportId;
            document.getElementById("exportView").setAttribute("href", TakeHref);
        });

this code running successfully in my app, thank you all.

Vasantha Raj
  • 637
  • 1
  • 6
  • 22
0

I think you have to include the file ending to the url (e.g. .txt)

$.ajax({
   url : "/download/myDir/exportFile.txt",
   ...
})
bloC
  • 526
  • 3
  • 16
0

The answer is: No you can't.

AJAX requests are done within a rendered page in the browser. They request the content of a file and that is stored inside the XMLHTTPObject. The response header for content-type will not make a difference and is ignored by the browser.

To be more precise:

An AJAX call is executed inside a page for which the response header is set to TEXT/HTML, that means that the content of the file is requested by AJAX. The response header will not be reset by the call and therefor will not trigger a download.

When clicking a link, the response header describing the content of the file is sent to the page by the JAVA code resulting in a response that is treated as a download by the browser.

Mouser
  • 13,132
  • 3
  • 28
  • 54
  • kindly help me sir, then how can i download the file with out using html tag, – Vasantha Raj Aug 10 '15 at 09:07
  • Not, a download should always be user triggered. It's a safety feature, where ajax requests can be done by code. – Mouser Aug 10 '15 at 09:08
  • Well there is one disgusting hack I can think of. Call upon the file, let it return some javascript code/meta tag that reload a page with a different url. Use print that data to a opened window. This will trigger the download. It's a lot of fuss, using a download link would work better. – Mouser Aug 10 '15 at 09:11
0

you should use ajax call and the trick is defining dataType then the response will be what the .txt file contains.

$.ajax({
        url : "some-file.txt",
        dataType: "text",
        success : function (data) {
            // set text to preferred DOM
            $("THE-DOM").html(data);
        }
    });
  • Nope, will just print jibberish to the page for files other than txt files With TXT it will print the txt file to the page, not provide it as a download. The page headers are already set and cannot be changed. Page will be treated as `TEXT/HTML`. – Mouser Aug 10 '15 at 08:41
  • @Masood Rezazadeh , sir i am using rest , that url pattern connect to the path only, some.txt file in this path(/home/cerdik/Desktop/some.text). – Vasantha Raj Aug 10 '15 at 08:44
  • @VasanthaRaj u should put file in your public directory where other assets are accessible – Masood Rezazadeh Aug 10 '15 at 09:01
  • @MasoodRezazadeh That is not necessarily needed. You can load it with server side scripting. Provide the correct headers and present it as a download. – Mouser Aug 10 '15 at 09:19
0

If you really need JS intervention to have your params changed than this code snippet should do. Not a good way to do though.

//your JS function to manipulate the url
function downloadFile(){
  var url = "/download/myDir/exportFile";//+your extra params
  $('#fake').prop({'src':url});
}
<a href="#" onclick="downloadFile()" id="exportViewRule">Export</a>
<iframe name="fake" id="fake" style="display:none;"></iframe>
joyBlanks
  • 6,419
  • 1
  • 22
  • 47