我正在使用express-fileupload模块。我还写了一些jquery来尝试使之工作。我大部分时间看到的是将图像发送到数据库重新显示的情况。但是,就我而言,将图像附加到输入元素后,我希望在提交最终表单之前通过img
标签显示图像。我期待收到任何人的来信。谢谢。
// app.js
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
require('dotenv').config();
var bodyParser = require('body-parser');
var session = require('express-session');
var expressValidator = require('express-validator');
var fileUpload = require('express-fileupload');
//Connect to db
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('connected to mongoDB');
});
//Init app
var app = express();
//View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//Set public folder
app.use(express.static(path.join(__dirname, 'public')));
//Set global errors variable
app.locals.errors = null;
// Express FileUpload middleware
app.use(fileUpload());
//Body Parser Middleware
//
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//express session middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
// cookie: { secure: true }
}));
//express-validator middleware
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value: value
};
}
}));
//Express messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
//set routes
var pages = require('./routes/pages');
var adminPages = require('./routes/admin_pages');
var adminCategories = require('./routes/admin_categories');
var adminProducts = require('./routes/admin_products');
app.use('/admin', pages);
app.use('/admin/pages', adminPages);
app.use('/admin/categories', adminCategories);
app.use('/admin/Products', adminProducts);
var port = 3000 || process.env.PORT;
app.listen(port, function() {
console.log('Server started on port ' + port);
});
// add_products.js
router.get('/add-product', function (req, res) {
var title = "";
var desc = "";
var price = "";
Category.find(function(err, categories) {
res.render('admin/add_product', {
title: title,
desc: desc,
categories: categories,
price: price
});
});
});
// add_product.ejs
<%- include('../_layouts/adminheader') %>
<h2 class="page-title">Add a product</h2>
<a href="/admin/products" class="btn btn-primary">Back to all products</a>
<br><br>
<form method="post" action="/admin/products/add-product" enctype="multipart/form-data">
<div class="form-group">
<label for="">Title</label>
<input type="text" class="form-control" name="title" value="<%= title %>" placeholder="Title">
</div>
<div class="form-group">
<label for="">Description</label>
<textarea class="form-control" name="desc" cols="30" rows="10" placeholder="Description"><%= desc %></textarea>
</div>
<div class="form-group">
<label for="">Category</label>
<select name="category" class="form-control">
<% categories.forEach(function(cat) { %>
<option value="<%= cat.slug %>">
<%= cat.title %>
</option>
<% }); %>
</select>
</div>
<div class="form-group">
<label for="">Price</label>
<input type="text" class="form-control" name="price" value="<%= price %>" placeholder="Price">
</div>
<div class="form-group">
<label for="">Image</label>
<input type="file" class="form-control" name="image" id="img">
<img src="#" id="imgPreview" alt="" />
</div>
<button class="btn btn-default">Submit</button>
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#imgPreview").attr('src', e.target.result).width(100).height(100);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#img").change(function () {
readURL(this);
});
</script>
<%- include('../_layouts/adminfooter') %>