0

I an trying to create a service which takes a xlsx template file and response a populated xlsx file with some values. What I have done so far is,

index.html

<input name="file" type="file" onchange="callthis()"/>

script.js

// callthis sends the file from client to server
function callthis() {
var formData = new FormData($(this).files[0]);

    $.ajax({
        url: '/uploadTemplate',
        type: 'POST',
        data: formData,
        success: function (data) {
            console.log(data);
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
}

serverRouter.js

router.post('/uploadTemplate', function(req, res, next){
    let uploadedFilePath = null;

    // I'm using multer for handling formdata in the server
    var upload = multer({ dest: Locator.temp.temp });

    //configure the multer
    var storage = multer.diskStorage({
        destination: function (req, file, callback) {
            callback(null, Locator.temp.temp);
        },
        filename: function (req, file, callback) {
            uploadedFilePath = file.fieldname + '-' + Date.now() + '.xlsx';
            callback(null, uploadedFilePath);
        }
    });

    var upload = multer({ storage : storage}).single('file');

    //in here i am uploading the file.

    //and reading the file ugin XLSX modules.

    //doing some changes to xlsx json object

    //and write the data to a file in a temp folder

    //i'm using res.download method to send downloadable file back to client 
     res.download(Path.join(Locator.temp.temp, uploadedFilePath));
    });
})

Using above codes, i could upload the file and get response. success method prints out details i added with some unreadable characters. But i could not download the file.

How can i download the file. Are there any different and better approach for this situation.

s1n7ax
  • 2,750
  • 6
  • 24
  • 53
  • Possible duplicate of [res.download() not working in my case](http://stackoverflow.com/questions/20176982/res-download-not-working-in-my-case) – zola Jan 11 '17 at 03:34
  • nope. it's working when we navigate to url. but in this case i dont want to navigate to the url – s1n7ax Jan 11 '17 at 04:50

1 Answers1

0

You can't attach a download to an AJAX request. You will have to send the download URL in the AJAX response and then have your client side script open the URL

In the server:

let response = {downloadUrl: Path.join(Locator.temp.temp, uploadedFilePath)}
res.json(response)

In the client:

window.open(ajaxResponse.downloadUrl);
David Jones
  • 2,879
  • 2
  • 18
  • 23