【问题标题】:How to save file paths to my database using Node.js?如何使用 Node.js 将文件路径保存到我的数据库?
【发布时间】:2021-08-05 13:06:08
【问题描述】:

我有一个简单的 HTML 表单,可以让用户上传文件。这比在提交时通过 auth/post/ 发布。

我的路线是这样的:

const express = require('express');
const authController = require('../controllers/auth');
const router = express.Router();
const multer  = require('multer');

function checkFileType(file, cb){
    const filetypes = /jpeg|jpg|png|gif|mp3|ogg|aac|wav/;

    if (req.fileValidationError) {
        return res.send(fileValidationError);
    }

    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = filetypes.test(file.mimetype);
    if(mimetype && extname){
      return cb(null,true);
    } else {
      cb('Format not allowed!');
    }
}

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null,'./user_uploads/')
    },
    fileFilter: function(req, file, cb){
        checkFileType(file, cb);
    },
    filename: function (req, file, cb) {
        let ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
        cb(null, Date.now() + ext)
    }
});
const upload = multer({
    storage: storage
}).single('user_file');

router.post('/post', upload, function(req, res, next){ res.locals.storage = storage; next();}, authController.post);

module.exports = router;

当您使用“上传”时,它会检查您是否实际放入了某些内容、其格式是否正确、更改文件名并将其保存到临时文件夹中。

我现在想获取存储变量,也就是我的 authController.post 的文件路径/名称/扩展名。

这是一个带有导出功能的控制器,其他所有内容都保存到数据库中。如何将路径变量传递给它?

供参考,它看起来像这样(我需要将路径放入user_path:_______):

exports.post = (req, res, next) => {
    let { name, title, cat, con, user_file } = req.body;
    const time = new Date().toJSON().slice(0, 19).replace('T', ' ');
    let cat_id = 0;

    if(req.files) user_file.fileName = req.file.filename;

    db.query("SELECT id FROM cat WHERE cat_name = ?", [cat], async function(err, results) {
        if (!err)
            cat_id = results[0].id;
        else
            console.log(err);

        const ID = await promisify(jwt.verify)(req.cookies.scrooc, process.env.jwtsecret);
        const id = ID.id;

        db.query('INSERT INTO posts SET ?', {user_id: id, cat_id: cat_id, time: time, title: title, content: con, user_file: res.locals.storage, reply: 0 }, (error, results) => {
            if(error)
                console.log(error);
            else
                res.status(200).redirect('/post');
        });
    });
 };

【问题讨论】:

    标签: javascript mysql node.js filesystems


    【解决方案1】:

    我认为您应该尝试编写一个文本字段(Python 中的 QLineEdit),将文件名路径设置为文本字段,然后在将值插入数据库期间使用插入语句将文本字段的内容保存到数据库中。例如,使用 Python,您可以通过以下方式实现:getfile 是我的函数的名称,您可以为自己的函数命名,但记得调用它。 photoinfo 是我的 QLineEdit 的名称,在 Java 中,如果我还记得的话,它被称为 JTextField。所以尝试使用我的代码中的逻辑,看看它是否可以解决你的问题。

    '''    def getfile(self):
        self.file_name = QtWidgets.QFileDialog.getOpenFileName(None, "Open", "", "All Files (*);;JPG Files(*.jpg)")
        try:
            if self.file_name[0] != '':
                print("success")
                self.photoInfo.setText(self.file_name[0])
            else:
                print("error")
        except Exception as e:
            print(e)
    

    【讨论】:

      【解决方案2】:

      我最终只是在路线中完成了全部功能。可能不是那么干净,但它确实有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-29
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        • 2016-11-22
        • 2017-04-15
        相关资源
        最近更新 更多