问题
I have created a simple node solution which contains a form and on that submit the form it will display the image that is being inserted in the form.
app.js
const app = express()
app.use(express.static('public'))
app.engine('hbs',handlebars({
layoutsDir : __dirname + '/views/layouts',
defaultLayout : "mainlayout",
extname : "hbs",
partialsDir : __dirname + '/views/partials'
}))
app.use("/uploader", imgUploader)
app.set('view engine','hbs')
impUpload.js
const express = require('express')
const route = express.Router();
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))
}
})
const upload = multer({
storage: Storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
}
}).single('myImage');
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 (extname && mimeType) {
return cb(null, true)
}
else {
cb('Error: Images Only!!!');
}
}
route.get("/", (req, res) => {
console.log("inside imgupload folder")
res.render("fileUpload")
})
route.post("/uploaded", (req, res) => {
upload(req, res, (error) => {
if (error) {
res.render("fileUpload", { message: error })
}
else {
if (req.file == undefined) {
res.render("fileUpload", { message: 'Please upload a file' })
}
else {
res.render('fileUpload', {
message: 'File Uploaded Successfully',
file: `uploads/${req.file.filename}`
});
}
}
})
})
module.exports = route
fileUpload.js
<div class="container">
<h1>file upload</h1>
{{message}}
<form action="/uploader/uploaded" method="post" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input name="myImage" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn n">Submit</button>
</form>
<br>
</div>
<div>
{{#if file}}
<img src="{{file}}" class="responsive-img">
{{/if}}
</div>
Currently, my solution is structured as below
I am getting the error in the console
GET http://localhost:3000/uploader/uploads/myImage-1589223958713.PNG 404 (Not Found)
I am not getting why it's trying to find that img in the uploader/uploads although I have defined public folder in the app.js
But when trying the same code in the app.js it's working absolutely fine.
also if I try express().use(express.static(path.join(__dirname , '../public'))) in the imgupload.js then i am getting the error Not allowed to load local resource: file:///C:/arunoday/node/login_express_mongo/public/uploads/myImage-1589220613014.PNG
any help would be appreciated.
回答1:
This is just how browser's handle relative paths.
You have a Handlebars template that contains the following:
<img src="{{file}}" class="responsive-img">
The value of file
is set to uploads/${req.file.filename}
, which becomes something like uploads/myImage-1589223958713.PNG
.
When your template is executed with above value for file
you get:
<img src="uploads/myImage-1589223958713.PNG" class="responsive-img">
When the browser sees a relative URL, like uploads/myImage-1589223958713.PNG
, it has to figure out the absolute URL. Since this relative URL does not begin with a /
, the browser thinks it is a child path of the current page URL.
If the current page URL is http://localhost:3000/uploaded/uploader
, the browser thinks your uploads/myImage-1589223958713.PNG
URL is a child of http://localhost:3000/uploader/
and so produces: http://localhost:3000/uploader/uploads/myImage-1589223958713.PNG
.
To get the correct URL, you want to set the value for file
so that it includes the full path:
file: `/uploads/${req.file.filename}`
Update:
Note that /public
should not be used included in the value for file
because the /public
directory is registered with express as a directory in which to look for static assets.
来源:https://stackoverflow.com/questions/61737643/how-express-forming-the-img-url