Eggjs file download service

Time:2021-4-11

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.
    ctx.attachment(fileName,{
        fallback:true,
        type:'attachment' // [string] attachment/inline
    });
    const fileSize = fs.statSync(filePath).size;
    ctx.set('Content-Length',fileSize) 
    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";
xhr.open('GET',url,true);
//In progress
xhr.onprogress = function(ev){
    // console.log(ev)
}
//When loading
xhr.onload = function(ev){
    if(xhr.readyState===4&&xhr.status===200){
        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
        a.click()
    }
}
xhr.send()

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 […]