koa-body, nodejs koa middleware file upload, build file service

Posted by Cronje on Tue, 01 Oct 2019 03:41:21 +0200

Preface

koa as the solution of node service, koa-body As the middleware of koa, it is friendly to upload files and POST JSON, set the size of json and upload files. koa-static provides service static file access

demand

Upload picture interface, save the file directory "Year/Month/SDK_20190904153509.png" according to the current date, to divide the year and month for file management.

install

npm install koa koa-router
npm install koa-body
npm install koa-static
//To save to a local project, you need to add a suffix -- save-dev

app.js

const koa=require("koa")
const Router=require('koa-router')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const {upload}= require('upload.js')


const router=new Router()
const app=new koa()

// koa-body Intermediate Plug-in File Submission and form-data
app.use(koaBody({
    formLimit: '1mb',
    multipart: true, // Allow multiple files to be uploaded
    formidable: {
        maxFileSize:200 * 1024 * 1024 //Upload file size
        keepExtensions: true, //  Extensions to save images
    }
}))
// Configuring Static Resource Loading Middleware
app.use(koaStatic(
    path.join("/f\upload") //Read static file directories
))

// Post
router.post('/login',async (ctx,next)=>{
    console.log('login Success!')
    //ctx.request.body is used to get post parameters
    ctx.body=ctx.request.body;
})
//koa-router
app.use(upload()) //  Route
app.use(route).use(router.post('/upload',upload));  

app.listen(3000)

upload.js

/* 
    File upload 
 */
const fs = require('fs');
const path = require('path');
const dateFormat = require('../utils/dateFormat.js')
const upload= {
        UPLOAD: '/upload',
        IMAGE: '/image/',
        FILE: '/file/',
        MAXFILESIZE: 200 * 1024 * 1024, //Upload file size
    }
// Create a file directory
const mkdirFile = (path) => {
    let pathList = path.split('/');
    let fileDir = ''
    pathList.forEach(i => {
        if(i) {
            fileDir += ('/' + i)
            if(!fs.existsSync(fileDir)) {
                fs.mkdirSync(fileDir, err => {
                    LogFile.info('Create failure', err)
                    return
                });
            }
        }
    })
}
//Save file
const saveFile = (file, path) => {
    return new Promise((resolve, reject) => {
        let render = fs.createReadStream(file);
        // Create a write stream
        let upStream = fs.createWriteStream(path);
        render.pipe(upStream);
        upStream.on('finish', () => {
            resolve(path)
        });
        upStream.on('error', (err) => {
            reject(err)
        });
    })
}

/**
 * File upload
 * ps Generate file name SKD_date
 *     File paths are stored according to year and month
 */
const uploadImg = async ctx => {
    var time = Date.parse(new Date())
    let date = dateFormat.dateFormat(time, 'yyyyMMddhhmmss');
    let file = ctx.request.files.file;
    let fileName = 'SKD_ '+ upload.UPLOAD + upload.IMAGE //Upload and save directory
    let fileYear = date.substring(4, 8) + '/' +
        date.substring(8, 10);
    let tail = file.name == 'blob' ? 'png' : file.name.split('.').pop()
    let filePath = path.join(fileName, fileYear, date + '.' + tail); //Stitching file names according to time
    await mkdirFile(fileName + fileYear)         //Create a file directory
    await saveFile(file.path, filePath).then(su => {
        let uplaod_img = su.substring(upload.UPLOAD.length, su.length)
        ctx.body = {
            error_code: 10000,
            error_message: 'Successful upload of files',
            realName: uplaod_img,
        }
    }).catch(err => {
        ctx.body = {
            error_code: 20008,
            error_message: 'Failed to upload file!',
        }
    })
}

module.exports = {
    uploadImg
};

ps: fs, path npm installation, date tool class can be viewed dateFormat.js

Picture Access Address: http://localhost:3000/image/2019/09/SDK_20190904153509.jpg
Project address https://github.com/shanyanwt/...

May you remain independent thinking, not humble, not overly aggressive, and try to grow into your own likes.

I am a lonely wolf... Welcome star

Topics: Javascript npm JSON github