gpt4 book ai didi

javascript - Node.js:Multer 上传 promise ?

转载 作者:搜寻专家 更新时间:2023-10-31 23:31:17 25 4
gpt4 key购买 nike

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

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

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

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?

最佳答案

这个解决方案对我有用:

为此需要 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”方法,这将使您有可能避免所谓的“回调 hell ”。它将基于回调的函数转换为基于 Promise 的函数。

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

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 !

关于javascript - Node.js:Multer 上传 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45540560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com