首页 > 解决方案 > 如何使用node.js将pdf保存在文件夹中

问题描述

目前我使用 node.js 将图像保存在一个文件夹中。但现在我需要保存 pdf 文档。我应该进行哪些调整,以便它接受 pdf 文档并将其保存在另一个文件夹中。

这是我保存图像的代码:

const multer = require('multer');
var uuid = require('uuid');
const path = require('path');
uuid=uuid.v4();
console.log(uuid);

app.set('views', path.join(__dirname, 'views'));

const storage = multer.diskStorage({
    destination: path.join(__dirname, 'public/img/uploads'),
    filename: (req, file, cb, filename) => {

        cb(null, uuid() + path.extname(file.originalname));
    }
}) 
app.use(multer({storage}).single('image'));
app.use(express.static(path.join(__dirname, 'public')));

标签: node.jsmulter

解决方案


正如您提供的上述代码适用于图像,您可以更改 pdf 的目标文件夹。

const imageFolderPath = 'public/img/uploads';
const pdfFolderPath = 'public/pdf/uploads';

const storage = multer.diskStorage({
    destination: (req, file, cb ) => {
        if (file.fieldname === 'img') { // check the fieldname
            cb(null, imageFolderPath);
        }
        else {
            cb(null, pdfFolderPath);
        }
     },
    filename: (req, file, cb, filename) => {
        cb(null, uuid() + path.extname(file.originalname));
    }
}) 

检查字段名称对于更改路径很重要。您可以在目标方法中创建逻辑。

注意:上传前请确保pdf文件夹的路径存在。


推荐阅读