【问题标题】:Multer file address to upload folder is not well formatted in MySQL database上传文件夹的 Multer 文件地址在 MySQL 数据库中格式不正确
【发布时间】:2019-01-11 09:38:01
【问题描述】:

我使用 Multer Node.js 模块将图像上传到上传文件夹,并且图像上传正常,并且正确的路径已传递到 MySQL 数据库,但文件(图像)的文件路径没有像我预期的那样格式化.

我的意思是主文件夹、子文件夹和文件(图像)实际名称之间没有斜线 (/),尽管扩展名是正确的。

const storage = multer.diskStorage({
    destination: "./public/upload/",
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() +
            file.originalname)
    }
})

const upload = multer({
    storage: storage
})

但这是我提出请求时从数据库获取的数据类型

[
    {
        "id": 3,
        "name": "samsung galax s8",
        "brand": "samsung",
        "image": "publicuploadfile-1547151173379tecno-spak-2.jpg",
        "category": "phone",
        "qty": "6",
        "price": "50000",
        "created_at": "1/10/2019",
        "updated_at": "1/10/2019"
    }
]

这是我得到的图片file.path "publicuploadfile-1547151173379tecno-spak-2.jpg",

而不是像我所期待的 "public/upload/file-1547151173379tecno-spak-2.jpg"

请问如何将数据库的路径保存为正确的文件地址?

【问题讨论】:

    标签: javascript node.js multer file-format


    【解决方案1】:

    更新这个。

    var storage = multer.diskStorage({
      destination: function(req, file, callback) {
        callback(null, './uploads')
      },
      filename: function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
      }
    })
    

    【讨论】:

      【解决方案2】:

      有一个类似的问题,我看到当我使用原始 sql 查询来保存 req.file.path mysql 引擎会去掉我的反斜杠“\”但是当我使用批量插入来一次插入多个文件 url 时它做到了不要去掉反斜杠。

      例如, temp[i] = {'recordedWebinarVideo': req.files[i].path}

        con.query('UPDATE `courses` SET `Recorded_URL` = "'+temp[i].recordedWebinarVideo+'" 
         WHERE `CourseID`="'+req.params.id+'" ', (err,data)=>{
          if(err)
          console.log(err)
          else{
            console.log(data)
      
          }
        })
      

      结果:反斜杠已删除

      然而, 与

      con.query('INSERT INTO course_extra_resources (file_path, course_id) 值?', [temp.map( i => [i.files, req.params.id])], (err,data)=> { 如果(错误) 控制台日志(错误); 别的{ 控制台日志(数据) res.status(200).json(数据) } }) 反斜杠是相关的,mysql 以正确的格式保存了 url。

      【讨论】:

        猜你喜欢
        • 2018-11-11
        • 1970-01-01
        • 2018-02-25
        • 2016-10-20
        • 2021-10-07
        • 2018-07-21
        • 1970-01-01
        • 2013-02-14
        • 2011-12-27
        相关资源
        最近更新 更多