如何在node js中用express和multer保存pdf文件。

问题描述 投票:0回答:1

我在使用一个multer api,我在内存中保存文件,因为我需要上传图片和pdf,我需要处理图片。我可以上传图片,但我不能上传pdf文件。

node.js express multer
1个回答
0
投票

这可能会帮助你

// Set storage engine
const storage = multer.diskStorage({
  destination: "./uploads",
  filename: function(req, file, cb) {
    // null as first argument means no error
    cb(null, Date.now() + "-" + file.originalname);
  },
});



  let encode_file = null;
  let fileName = "";
  if (req.file) {
    fileName = req.file.originalname;
    var filepath = path.join(__dirname, req.file.path);
    console.log(filepath);
    var stream = fs.readFileSync(filepath);
    encode_file = stream.toString("base64");
  }

0
投票

好吧,这是我的代码... 我真的希望能帮助你。

const express = require('express');
const multer = require('multer');
const app = express();

const storage =
    multer.diskStorage({
    destination: path.join(__dirname, 'public/img/'), // destination folder
    filename: (req, file, cb) => {
        cb(null, uuid.v4() + path.extname(file.originalname));
    }
});

const upload =
multer({
storage,
dest: path.join(__dirname, 'public/img/'), // destination folder
limits: {fileSize: 3500000}, // size we will acept, not bigger
fileFilter: (req, file, cb) => {
    const filetypes = /jpeg|jpg|png|gif|pdf/; // filetypes you will accept
    const mimetype = filetypes.test(file.mimetype); // verify file is == filetypes you will accept
    const extname = filetypes.test(path.extname(file.originalname)); // extract the file extension
    // if mimetype && extname are true, then no error
    if(mimetype && extname){
        return cb(null, true);
    }
    // if mimetype or extname false, give an error of compatibilty
    return cb("The uploaded file, isn't compatible :( we're sorry");
}
}).single('image'); // This is the field where is the input type="file", we only accept 1 image
app.use(upload);

视图是这样的

app.post('/add', async (req, res) => {
const { originalname, mimetype, destination, filename, path, size} = req.file;
const newImage = {
    originalname,
    mimetype,
    destination,
    filename,
    path,
    size
};
await pool.query('Insert Into imagen set ?', [newImage]);
res.send('image uploaded');
});
© www.soinside.com 2019 - 2024. All rights reserved.