Eggjs file download service


Background method code

async download() {
    const {ctx,app} =this;
    let fileName = 'hello.js'
    const filePath = path.resolve(app.config.static.dir,fileName);
    //  ctx.attachment ([file name], [options]) sets content disposition to "attachment" to indicate that the client prompts to download.
        type:'attachment' // [string] attachment/inline
    const fileSize = fs.statSync(filePath).size;
    ctx.set('Content-Disposition',`attachment; filename=${fileName}`)
    ctx.body = fs.createReadStream(filePath);

Front desk code

Using blob and ajax

What is blob

Blob stores a lot of binary data. Blob has two properties: size and type. We can use blob object to store the file stream returned from the background

const xhr = new XMLHttpRequest();
const url ="http://localhost:7001/download";'GET',url,true);
//In progress
xhr.onprogress = function(ev){
    // console.log(ev)
//When loading
xhr.onload = function(ev){
        const type =  xhr.getAllResponseHeaders('content-type')
        var blob = new Blob([xhr.response],{type});
        var newUrl = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = newUrl;
        a. Download ='a.js'; // the file name here can be obtained from where the file is requested to be downloaded

Such a simple file download service is complete

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]