我需要有关如何使用multer在express js中上传图像的帮助,到目前为止,我已经完成了两种操作:
当我测试时,代码将运行直到执行功能UploadDocumentDriver并在编写的控制台日志文件中显示文本(请参见上载js文件)。但是我选择的文件都没有上载到目录。
这是我的代码:
route.js
const express = require('express');
const router = express.Router();
const DriverCtrl = require('../controllers/Ctrl_Driver');
router.post('/', DriverCtrl.createDriver);
DriverController.js
const bcrypt = require('bcrypt');
const Driver = require('../models/driver');
const DriverStreamLocation = require('../models/driverStreamLocation');
const { body, validationResult } = require('express-validator');
const { upload } = require('../helper/upload');
const multer = require("multer");
let storage = multer.memoryStorage();
const fs = require("fs");
const path = require('path');
const { driverValidationRules, validate } = require('../validators/driverValidator');
exports.createDriver = (req, res, next) =>
{
const imageUpload = multer({ storage: storage, limits: { fileSize: 1000000 },
fileFilter: function (req, file, cb) {
let filetypes = /jpeg|jpg/;
let mimetype = filetypes.test(file.mimetype);
let extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb(new Error('Invalid IMAGE Type'))
}
}).fields([ { name: "0", maxCount: 1 }, { name: "1", maxCount: 1 }, { name: "2", maxCount: 1 },
{ name: "3", maxCount: 1 } ]);
imageUpload(req, res, (multerErr) =>
{
if(multerErr){
let errors = [];
errors.push({msg : "Gambar harus memiliki format jpg atau jpeg"});
return res.render('navigation', {
name : 'request',
page : 'drivers/register_driver',
errors : errors,
});
}else
{
// return console.log(req.files, req.body);
// return next();
[
// username must be an email
body('driver_first_name')
.not().isEmpty().withMessage('Nama depan wajib diisi').bail()
.isLength({min : 3}).withMessage('Nama depan minimal 3 karkter').bail(),
body('driver_last_name')
.not().isEmpty().withMessage('Nama belakang wajib diisi').bail()
.isLength({min : 3}).withMessage('Nama belakang minimal 3 karakter').bail(),
body('driver_phone')
.not().isEmpty().withMessage('No HP wajib diisi').bail()
.isLength({min : 3}).withMessage('Minimal Karakter : 3').bail(),
body('driver_email')
.isEmail().withMessage('Format Email salah'),
body('driver_gender')
.not().isEmpty().withMessage('Gender wajib diisi'),
body('driver_job_type')
.not().isEmpty().withMessage('Tipe pekerjaan wajib diisi'),
body('driver_city')
.not().isEmpty().withMessage('Kota wajib diisi')
]
const result = validationResult(req);
var errors = result.errors;
if (errors == 0)
{
var FullNamePerson = req.body.driver_first_name + req.body.driver_last_name ;
// start next execution
const files = req.files;
// const date = Date;
const fileName = Date.now();
let images = new Array();
let limit = Object.keys(files).length;
for(let i=0; i<limit; i++)
{
images.push({
filename: fileName + "-" + FullNamePerson + "-" + [i],
originame: files[i][0]['originalname'],
mimetype: files[i][0]['mimetype'],
size: files[i][0]['size'],
buffer: files[i][0]['buffer']
})
}
// return console.log(images);
let module = 'driver';
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.driver_password, salt);
var driver =
{
first_name : req.body.driver_first_name,
last_name : req.body.driver_last_name,
password : hash,
phone : req.body.driver_phone,
email : req.body.driver_email,
gender : req.body.driver_gender,
job_type : req.body.driver_job_type,
city : req.body.driver_city,
file : images,
account_number : req.body.no_rekening,
account_name : req.body.nama_pemilik_rekening,
occupation: req.body.pekerjaan_saat_ini,
referral_code : req.body.kode_referensi
};
Driver.create(driver, function(err, driver) {
if (err)
{
res.json({
error : err
})
}
else
{
const create = new DriverStreamLocation({
_id: driver._id, driver : driver.first_name
})
create.save(function(err, params) {
if (err)
{
res.json({
error : err
})
console.log(err);
} else {
console.log('DriverStreamLocation passed ' +params);
if (process.env.NODE_ENV_CONNECTION == "local") {
upload(driver._id, fileName, module, images);
} else {
console.log("none");
}
}
});
}
});
return res.redirect('/drivers/data_mitra_ojek');
}
console.log(errors);
return res.render('navigation', {
name : 'request',
page : 'drivers/register_driver',
errors : errors,
driverFirstName : req.body.driver_first_name,
driverLastName : req.body.driver_last_name,
driverPhone : req.body.driver_phone,
driverEmail : req.body.driver_email,
driverGender : req.body.driver_gender,
driverJobType : req.body.driver_job_type,
driverCity : req.body.driver_city,
accountNumber : req.body.no_rekening,
accountName: req.body.nama_pemilik_rekening,
Occupation: req.body.pekerjaan_saat_ini,
referralCode: req.body.kode_referensi
})
}
});
};
Upload.js
const fs = require('fs');
const upload = (user, fileName, module, DriverDocuments) => {
switch(module)
{
case('driver') :
return UploadDocumentDriver(user, fileName, module, DriverDocuments);
break;
case('merchant'):
return UploadDocumentMerchant(user, fileName, module, DriverDocuments);
break;
default :
console.log("none of these are match!");
}
}
function UploadDocumentDriver(user, fileName, module, DriverDocuments)
{
// return console.log(DriverDocuments);
let dir = "./uploads";
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
console.log('Directory Uploads Created!');
}
dir = dir + "/" + module;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
console.log('Directory Driver Created!');
}
dir = dir + "/" + user;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
console.log('Directory User Created!');
}
DriverDocuments.forEach(element => {
fs.writeFile(dir + "/" + fileName + ".jpg", element.buffer, function (err) {
if (err) {
return console.log(err);
}
console.log('file written!');
});
});
}
function UploadDocumentMerchant(user, fileName, module, fileBuffer)
{
}
module.exports = {
upload
}
Register.ejs
<div id="layoutSidenav_content">
<main>
<div class="container-fluid">
<h1 class="mt-4">Register Driver</h1>
<ol class="breadcrumb mb-4">
<li class="breadcrumb-item active">Data Mitra Ojek</li>
<li class="breadcrumb-item active">Register Driver</li>
</ol>
<form style="width:70%;" action="/drivers/" method="POST" enctype="multipart/form-data">
<div class="card mg-3">
<div class="card-header">
<li class="breadcrumb-item active">Form Input Register Driver</li>
</div>
<div class="card-body form_error">
<% if(locals.errors){%>
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria- hidden="true">×</button>
<strong>PERIKSA KEMBALI INPUTAN ANDA.</strong>
<br>
<% Object.values(errors).forEach(function(error){ %>
* <%= error.msg %> <br>
<% });%>
</div>
<% } %>
<div class="form-row">
<div class="form-group col-md-6">
<label>Nama Depan</label>
<input type="text" name="driver_first_name" class="form-control" value="<%= (!! locals.driverFirstName != '') ? driverFirstName : null %>" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Nama Belakang</label>
<input type="text" name="driver_last_name" class="form-control" value="<%= (!! locals.driverLastName != '') ? driverLastName : null %>" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Password</label>
<input type="password" name="driver_password" class="form-control" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>No HP</label>
<input type="number" name="driver_phone" class="form-control" value="<%= (!! locals.driverPhone != '') ? driverPhone : null %>" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Email</label>
<input type="email" name="driver_email" class="form-control" value="<%= (!! locals.driverEmail != '') ? driverEmail : null %>">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Gender</label>
<select class="form-control" name="driver_gender" id="genderSelect">
<option disabled selected value> -- Pilih gender -- </option>
<option class="red" value="male"> Laki-laki </option>
<option class="green" value="female"> Perempuan </option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Tipe Pekerjaan</label>
<select class="form-control" name="driver_job_type" id="jobSelect">
<option disabled selected value> -- Pilih tipe pekerjaan -- </option>
<option class="red" value="motorcycle"> Kojol Motor </option>
<option class="green" value="car"> Kojol Taxi </option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Kota</label>
<select class="form-control" name="driver_city" id="citySelect">
<option disabled selected value> -- Pilih kota -- </option>
<option class="red" value="surabaya"> Surabaya </option>
<option class="green" value="sidoarjo"> Sidoarjo </option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Upload KTP</label>
<br />
<input type="file" name="0" accept="image/*"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Upload SIM</label>
<br />
<input type="file" name="1" accept="image/*"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Upload STNK</label>
<br />
<input type="file" name="2" accept="image/*"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Upload SKCK</label>
<br />
<input type="file" name="3" accept="image/*"/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Nomor Rekening</label>
<input type="text" name="no_rekening" class="form-control" value="<%= (!! locals.accountNumber != '') ? accountNumber : null %>" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Nama Pemilik Rekening</label>
<input type="text" name="nama_pemilik_rekening" class="form-control" value="<%= (!! locals.accountName != '') ? accountName : null %>" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Pekerjaan saat ini</label>
<input type="text" name="pekerjaan_saat_ini" class="form-control" value="<%= (!! locals.Occupation != '') ? Occupation : null %>" id="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Kode Referensi (Tidak wajib)</label>
<input type="text" name="kode_referensi" class="form-control" value="<%= (!! locals.referralCode != '') ? referralCode : null %>" id="">
</div>
</div>
<button type="submit" class="btn btn-success float-right"><i class="icon-plus"></i>Tambahkan</button>
</div>
</div>
</form>
</div>
</main>
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © Your Website 2020</div>
<div>
<a href="#">Privacy Policy</a>
·
<a href="#">Terms & Conditions</a>
</div>
</div>
</div>
</footer>
</div>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
document.getElementById('genderSelect').value = "<%= (!! locals.driverGender != '') ? driverGender : null %>";
document.getElementById('jobSelect').value = "<%= (!! locals.driverJobType != '') ? driverJobType : null %>";
document.getElementById('citySelect').value = "<%= (!! locals.driverCity != '') ? driverCity : null %>";
</script>
<script>
$.ajax({
url: "/",
type: "POST",
dataType: "json",
data: {objectData: someObject},
contentType: "application/json",
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
console.log(data);
console.log('process sucess');
},
error: function() {
console.log('process error');
},
})
// swal("Success");
// if (locals.statusInsert == 200) {
// console.log('status insert received');
// }
// $.post({one: "two"}, function( data ) {
// $( "#cout" ).html( data );
// });
</script>
谢谢。