如何使用node.js将pdf保存在文件夹中

如何使用node.js将pdf保存在文件夹中,node.js,multer,Node.js,Multer,目前,我使用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,

目前,我使用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')));


正如您所提供的,上面的代码对图像很有效,您可以更改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));
    }
}) 

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


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

您在保存pdf时是否遇到任何困难,因为我可以看到它应该会保存文件。这里没有文件的筛选器。如果在执行此操作时出现错误,您可以将此添加到问题中。如果您正确保存了图像和pdf文件,则可以添加到Apoorva Chikara。但是我想把图像和pdf文件分到不同的文件夹中。这有帮助吗?