DennyHiu
DennyHiu

Reputation: 6060

Get file as AJAX's response?

I have a generic Ajax call routine that I use to call a function in node.js. This function reads a file from the server(xls mostly) then streams it back to client.

Here is my implementation in Node.js (server-side):

    // FILE DOESNT EXISTS BEFORE, 
    // FILE IS CREATED HERE THEN SAVED IN SERVER AS A FILE
    fs.readFile("/path/to/file.xlsx", function(err, file){
        res.setHeader('Content-Type', 'audio/mpeg');
        res.setHeader('Content-Disposition', 'attachment; filename=file.xlsx');
        res.write(file, 'binary');
        res.end();
    });

And this is my ajax call that I use.

$('#submit').click(function()
{
   $.ajax({
    url: '/',
    type:'POST',
    data: data,
    dataType: 'json',
    }).done(function(data) {
        console.log(data);
    });      
})

I successfully get binary data printed in my console (console.log(data)). My question is how to convert this data to a file with proper extension and then prompt the browser to save them ?

Any suggestion or another workaround ?

Upvotes: 0

Views: 1867

Answers (1)

guest271314
guest271314

Reputation: 1

Try using FileReader , Blob , a element , download attribute

$('#submit').click(function() {
   $.ajax({
    url: '/',
    type:'POST',
    data: data,
    dataType: 'json',
    }).done(function(data) {
        console.log(data);
        var reader = new FileReader();
        reader.onload = function(e) {
          $("a").attr({"href": e.target.result, "download":"filename"})
          .get().click()
        } 
        reader.readAsDataURL(new Blob([data]));
    });      
})

Upvotes: 3

Related Questions