问题
I am pretty new in node.js. I am unable to redirect the page /upload to another .html webpage. I mean, everything works fine, I upload the img file and the code goes to http://localhost:3000/upload page but I don't know how to automatically redirect to another. html file
Here is my HTML:
<div class="container">
<form action="/upload" method="POST" enctype="multipart/form-data">
<input name="myImage" type="file">
<input class="file-path validate" type="text" placeholder="Upload your file">
</div>
<button type="submit" class="btn">Submit</button>
</form>
</div>
and here my server file index.js
const express = require("express");
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: './public/uploads',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
//init upload
const upload = multer({
storage: storage,
limits: { filesize: 1000000 },
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
}).single('myImage'); //single image
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb("Error:images only");
}
};
const app = express();
app.use(express.static('./public'));
app.post('/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.json(err);
} else {
if (req.file == undefined) {
res.json("Error: No file selected")
} else {
res.json(`/${req.file.filename}`);
}
}
});
});
app.listen(3000, function(req, res) {
console.log("you are listening to port 3000");
});
I land on http://localhost:3000/upload and here I stay. How is possible to skip it and redirect this page automatically to another code html page? Thanks for any help
回答1:
You just have to use the res.redirect('/path/here/);
function under your route.
Full setup:
//Dependencies
const multer = require('multer');
//Multer DiskStorage Config
const diskStorage = multer.diskStorage({
destination: 'assets/profile_upload',
filename: (req, file, call_back) => {
//Prepend date to the filename or anything that makes
//the file unique so it won't be overwritten
call_back(null, Date.now() + '_' + file.originalname);
}
});
//Create Multer Instance
const upload = multer({ storage: diskStorage });
//Picture upload
//or app.post()
router.post('/upload-pic', upload.single('file'), (req, res) => {
//The redirection happens here.
console.log(req.file);
res.redirect('/your/path');
});
//Your code:
app.post('/upload', (req, res) => { ...
try doing app.post('/upload' ,upload.single('file'), (req,res) =>{ ...
来源:https://stackoverflow.com/questions/61341047/redirect-the-upload-webpage-got-from-a-form-post-request-in-node-js-npm-pack