簡體   English   中英

如何使用Node.js在數據庫中保存圖像路徑?

[英]How do I save Image path in the database using Node.js?

我正在使用node.js和express開發一個網頁。 我開發了一種表單,用戶可以在其中填寫自己的詳細信息並上傳其圖像。 映像文件應存儲在目錄中,而路徑應存儲在數據庫中。

我在Mongodb數據庫中使用Node.js. 該圖像已成功存儲在預期目錄中,但該路徑未存儲在數據庫中而不是路徑中,我發現了用於在數據庫中存儲該路徑的代碼(/posts/${image.name}請如何實現?

{

//Index.js

const path = require('path');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Post = require('./database/models/Post');
const fileUpload = require("express-fileupload");

const app = new express();
mongoose.connect('mongodb://localhost/node-js-test-blog', {   useNewUrlParser: true })
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload());

//the route responsible for storing the image in  posts directory and the path in the database

app.post('/posts/store', (req, res) => {
const { image } = req.files
image.mv(path.resolve(__dirname, 'public/posts', image.name), (error) => {

    Post.create({
        ...req.body,
        image: '/posts/${image.name}'//this code is what I get in the database instead of the path
    }, (error, post) => {
        res.redirect("/");
    });
})
});
app.listen(4000, () => {
console.log("application listening on port 4000")
})

}

//model
const mongoose = require('mongoose');
//collections represents entities in the application e.g users, posts, etc
//schema represents how to structure in the collections
const PostSchema = new mongoose.Schema({
description: String,
title: String,
content: String,
username: String,
image: String,
createdAt: {
    type: Date,
    default: new Date()
}
});

//the model itself is what will communicate with the database
const Post = mongoose.model('Post', PostSchema);


module.exports = Post;

}

//the code to display the (image) view from the database using node.js directive
<style="background-image: url('{{post.image}}')">

}

使用${}時需要使用反引號,否則字符串將按字面解釋:

更改此:

    image: '/posts/${image.name}'

對此:

    image: `/posts/${image.name}`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM