2

So the express docs have a download function in the following form:

res.download(cvUrl, cvName, function (err) {
  if (err) {
     // ...
  } else {
     // ...
  }
})

I think this would normally trigger the browser to download the file automatically, with the correct filename, as the response headers are correctly set and I'm receiving a file. But I'm handling the download like this:

this.admin.getCv(cvUrl).then(cv => {
    const url = window.URL.createObjectURL(new Blob([cv]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'test'); // how can I access the filename here?
    document.body.appendChild(link);
    link.click();
})

Is it possible to access the filename (cvName) on the frontend? Adding it as a second parameter seemed like the obvious solution, but didn't work. Any hints would be great,

Thanks,

Nick

**Edit:

import JRS from '../api/jrs';

export default class Admin {
    getCv (applicantId) {
        return JRS.get(`/admin/cvs/${applicantId}`);
    }
}

// JRS.js

import axios from 'axios';

export default axios.create({
    baseURL: 'http://localhost:8080',
    headers: {
        'Content-Type':  'application/json',
    },
    withCredentials: true
});
8
  • res.download will do no good for you if you are downloading it with ajax, better to make a link instead. if you need to send data, put it as url search parameters
    – Endless
    May 18, 2021 at 11:04
  • Hi @Endless, not entirely sure what you mean RE making a link? I've managed to get the filename + ext and what I think is the file itself to the frontend - although to be fair I'm suffering with unreadable content now when I try and open it...
    – NickW
    May 18, 2021 at 13:33
  • 1
  • 1
    Still think you should go with a server side solution instead of using axios or any ajax method
    – Endless
    May 19, 2021 at 13:36
  • 1
    jsfiddle.net/ydrsnvfz/1
    – Endless
    May 19, 2021 at 15:16

2 Answers 2

0

The download method adds a Content-Disposition header to the response, so you just need to read that.

It looks like your getCv function makes an HTTP request, extracts the body from the response, then resolves a promise with that body.

You'll need to modify the getCv function so it :

  • Reads the Content-Disposition header (how you do that depends on which HTTP API you are using)
  • Extracts the filename from it (something like contentDisposition.match(/filename=(.*)/))
  • Includes that in the data you are resolving the promise with (which will probably mean passing an object containing the filename and body instead of just the body)

Then you'll need to change your then callback so it handles that object instead of expecting the body directly.


That said, it would probably be easier to just link to the URL directly instead of fetching the data with JSON, converting it to a data: URL, generating a link and triggering a client on it.

7
  • Hi Quentin, yeah getCV() uses an axios instance to make a get request to the route needed. I'm now just trying to work out how to read the Content-Disposition header like you suggest. It's visible in the response - does that mean I don't need to set the Access-Control-Expose-Headers on the server? I've added my axios instance / getCv() function to the OP. Thanks for the help
    – NickW
    May 18, 2021 at 7:49
  • @NickW — You might need to set that too, but there was no suggestion there was anything cross-origin in the question.
    – Quentin
    May 18, 2021 at 7:50
  • My mistake - pretty new at this. Am I wrong in thinking that I should be able to access the headers on cv.data.headers? I mean I must be wrong because it's undefined, but that seems to be what's suggested in other answers. I've now set Access-Control-Expose-Headers.
    – NickW
    May 18, 2021 at 8:09
  • See github.com/axios/axios#response-schema - the headers are not inside the data.
    – Quentin
    May 18, 2021 at 8:11
  • XD They're not, you're right! Got the filename and ext working great thanks. Just to double check, you'd expect cv.data to be the file itself, right? I'm just getting unreadable content when I attempt to open it, and logging it shows a sequence of mostly ���
    – NickW
    May 18, 2021 at 13:35
0

This works for accessing the filename and ext, and fixes the problem I was having with axios/streams/unreadable content, in case it helps anyone else.

For the unreadable content, it was important to add the responseType to the request.

// Client side

axios.get('http://localhost:4000/download', {responseType: 'blob'}).then(res => {
    downloadFile(res);
}).catch(err => console.log(err));

const downloadFile = (res) => {
    const contentDisposition = res.headers['content-disposition'];
    const fileName = contentDisposition.split(';')[1].split('=')[1];

    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${fileName}`);
    document.body.appendChild(link);
    link.click();
}

// Server

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:2000');
    res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
    next();
});

app.get('/download', (req, res, next) => {
    const test = 'sample.doc';
    const fileUrl = path.join(__dirname, test);
    const fileName = path.basename(fileUrl);
    res.header('Content-Disposition', `attachment; filename=${fileName}`);
    const myReadableStream = fs.createReadStream(path.join(__dirname, test));
    res.status(200);
    myReadableStream.pipe(res);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.