Home > Blockchain >  How to ask for permission to download files on NextJS?
How to ask for permission to download files on NextJS?

Time:02-02

I have the following endpoint:

baseurl.com/api/v1/datasheet/format

Accesing this url will download specific information based on the datasheet. In Express, for example, I return this method if the format = json:

const generateJSON = (res, data) => {
    res.header('Content-Type', 'application/json');
    res.attachment('example.json');
    return res.send(data);
}

This works fine, but it downloads automatically the file as "example.json" without asking the user for his permission to download the file

My purpose is to have a button on my frontend (using NextJS) that will ask the user if he wants to download the file (the classic download or cancel prompt for downloads) and then open the file explorer, etc.

How can I do this? Is this something from the backend or frontend?

CodePudding user response:

Use Content-disposition: attachment; filename=example.json to trigger a Save as DIalog box.

const generateJSON = (res, data) => {
    res.header('Content-Type', 'application/json');
    res.header('Content-disposition', 'attachment');
    res.attachment('example.json');
    return res.send(data);
}


The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).

via https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#:~:text=The first parameter,parameters if present).

  •  Tags:  
  • Related