Node.js:多点上传承诺? [英] Node.js: Multer upload with promise?

查看:32
本文介绍了Node.js:多点上传承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个带有multer文件上传的快速路线.上传完成后,我想将图像编码为 base64 并发送响应.

I have this express route with multer file-upload. When the upload is complete, I would like to encode the image to base64 and send with response.

但是,当我这样做时,代码会尝试在将文件创建到文件夹之前执行 base64 编码.

However when I do it like this, the code tries to execute the base64 encoding before the file is created to the folder.

编辑:添加存储和上传功能

const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        if (!fs.existsSync('./uploads')) {
            fs.mkdirSync('./uploads');
        }
        let path = './uploads';
        callback(null, path);
    },
    filename(req, file, cb) {
        let fileExt = file.originalname.substring(file.originalname.lastIndexOf('.')).toLowerCase();
        if (!imageFilter(fileExt)) {
            return false;
        } else {
            cb(null, file.originalname);
        }
    },
    onError: function (err, next) {
        console.log('error', err);
        next(err);
    },
});

const upload = multer({
    storage,
    limits: {
        fileSize: 1000 * 1000 * 2 // 2 MB
    }
}).single('file');

router.post('/upload', function (req, res) {
    var directory = 'uploads';
    fs.readdir(directory, (err, files) => {
        if (err) throw err;
        for (var file of files) {
            fs.unlink(path.join(directory, file), err => {
                if (err) throw err;
            });
        }
    });
    upload(req, res, function (err) {
        if (err) {
            return res.status(404).json({
                success: false,
                message: 'File is too large. (Max 2MB)'
            });
        }

        var file = req.file;
        var base64str = base64_encode('./uploads/' + file.originalname);

        return res.status(200).json({
            success: true,
            url: 'http://' + ip.address() + ':' + constants.PORT + '/api/uploads/' + file.originalname,
            image: 'data:image/png;base64,' + base64str
        });
    });
});

实现正确操作顺序的最聪明方法是什么.可能是 promises 或 async/await?

What would be the smartest way to achieve the right order of operations. Possibly promises or async/await?

推荐答案

这个解决方案对我有用:

This solution worked for me :

此操作需要 Node v8.4.0

//app.js
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();

app.use(cors({credentials: true, origin: 'http://localhost:4200'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const Uploader = require('./Uploader.js');
const uploader = new Uploader();

app.post('/upload', uploader.startUpload);


//Uploader.js

const util = require("util");
const crypto = require("crypto");
const multer = require('multer');

class Uploader {

    constructor() {
        const storageOptions = multer.diskStorage({
            destination: function(req, file, cb) {
                cb(null, __dirname + '/uploads/')
            },
            filename: function(req, file, cb) {
                crypto.pseudoRandomBytes(16, function(err, raw) {
                    cb(null, raw.toString('hex') + Date.now() + '.' + file.originalname);
                });
            }
        });

        this.upload = multer({ storage: storageOptions });
    }

    async startUpload(req, res) {
        let filename;

        try {
            const upload = util.promisify(this.upload.any());

            await upload(req, res);

            filename = req.files[0].filename;
        } catch (e) {
            //Handle your exception here
        }

        return res.json({fileUploaded: filename});
    }
}

编辑:库util"为您提供了一个promisify"方法,这将使您有可能避免所谓的回调地狱".它将基于回调的函数转换为基于 Promise 的函数.

Edit : The library "util" provide you a "promisify" method which will give you the possibility to avoid something called the "callback hell". It converts a callback-based function to a Promise-based one.

这是一个理解我上面代码的小例子:

This is a small example to understand my code above:

const util = require('util');

function wait(seconds, callback) {
  setTimeout(() => {
    callback();
  }, seconds);
}

function doSomething(callType) {
  console.log('I have done something with ' + callType + ' !');
}

// Default use case
wait(2 * 1000, () => {
  doSomething('callback');
});

const waitPromisified = util.promisify(wait);

// same with promises
waitPromisified(2000).then((response) => {
  doSomething('promise');
}).catch((error) => {
  console.log(error);
});

// same with async/await

(async () => {
  await waitPromisified(2 * 1000);
  doSomething('async/await');
})();

将打印:

I have done something with callback !
I have done something with promise !
I have done something with async/await !

这篇关于Node.js:多点上传承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆