我是HTML,CSS,Javascript,Node.js和Electron框架的初学者,我试图弄清楚如何(通过JS从MongoDB数据库中)检索文本文件并在其中显示这些文件。桌面客户端。在HTML文件中,文件应显示在注释“文件(驻留在数据库中)应在此处显示”下的空格中(尽管存在类似的stackoverflow问题,但此问题与文件检索有关,而不是文件存储) 。
下面是HTML文件...
<!DOCTYPE html>
<!--This is the starting point of the desktop client development-->
<html>
<head>
<meta charset="UTF-8">
<title>Project Prime</title>
<!--Linking the html file to the css file-->
<link href="./index.css" type="text/css" rel="stylesheet">
<!--CSS file from Bootstrap website-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<!--This form allows users to upload and delete files in the server-->
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
<h1 class="title display-4 my-4">Project Prime Desktop</h1>
<!--Forms a connection to the server through HTTP POST request-->
<form action="http://100.76.164.19:3003/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input id="file" name="file" type="file" class="custom-file-input">
<label for="file" class="custom-file-label">Choose File:</label>
</div>
<!--A button that inserts files into the server-->
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
<!--Files (residing in the database) should be displayed under here -->
<!--JS scripts from Bootstrap-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
下面是我的JS文件...
//Middleware between server and the routes
//Express for building APIs
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const app = express()
// Node.js built-in Middleware
app.use(bodyParser.json())
app.use(methodOverride('_method'))
// To serve the static CSS file
app.use('/', express.static('./'))
// Mongo URI
const mongoURI = 'mongodb://projectPrime:projectPrime@projectprime-shard-00-00-wreg9.mongodb.net:27017,projectprime-shard-00-01-wreg9.mongodb.net:27017,projectprime-shard-00-02-wreg9.mongodb.net:27017/test?ssl=true&replicaSet=ProjectPrime-shard-0&authSource=admin&retryWrites=true'
mongoose.set('useNewUrlParser', true);
// Create mongo connection
const conn = mongoose.createConnection(mongoURI);
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
})
// Create storage engine
const storage = new GridFsStorage({url: mongoURI,file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err)
}
const filename = buf.toString('hex') + path.extname(file.originalname)
const fileInfo = {filename: filename, bucketName: 'uploads'}
resolve(fileInfo)
})
})
}
})
const upload = multer({storage});
// @route GET /
// @desc Loads homepage
app.get('/', (req, res) => {
res.sendFile('src/upload.html', {root: __dirname});
})
// @route POST /upload
// @desc Uploads file to DB
app.post('/upload', upload.single('file'), (req, res) => {
// res.json({file: req.file});
// Navigate back to the desktop client
res.redirect('/');
})
// @route GET /files
// @desc Display all files in JSON
app.get('/files', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files exist
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No files exist'
});
}
// Files exist
return res.json(files);
});
});
// @route GET /files/:filename
// @desc Display single file object
app.get('/files/:filename', (req, res) => {
gfs.files.findOne({filename: req.params.filename}, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// File exists
return res.json(file)
});
});
// @route DELETE /files/:id
// @desc Delete file
app.delete('/files/:id', (req, res) => {
gfs.remove({ _id: req.params.id, root: 'uploads' }, (err, gridStore) => {
if (err) {
return res.status(404).json({ err: err })
}
res.redirect('/')
})
})
module.exports = app
尝试的解决方案
将HTML文件转换为EJS文件后,我编写了EJS代码以显示Mongo存储的文件...
<% if(files) { %>
<% files.forEach(function() { %>
<div class="card card-body mb-3">
<% if(file.isImage) { %>
<img src="image/<%= file.filename %>" alt="">
<% } else { %>
<%= file.filename %>
<% } %>
<form method="POST" action="/files/<%= file._id %>?_method=DELETE">
<!-- Removes files from the DB upon button press-->
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
<% }) %>
<% } else { %>
<p>No files to show</p>
<% } %>