尝试上传图片,但从multer中未定义req.file

时间:2019-10-01 10:46:20

标签: node.js multer

我的代码非常简单,几乎遵循Multer git上的教程,但是我的req.file仍未定义:

这是我上传图片的html:

<form action="/product/upload_image" enctype="multipart/form-data" method="POST"> 

  <input id="product_image" type="file" name="product_image" accept=".png,.jpg,.jpeg"/>      

   <input type="submit" value="Upload image"/>
</form>

我的路线:

var multer = require("multer")
var upload = multer({ dest: "uploads/" })

router.post("/product/upload_image", upload.single("product_image"), function(req, res) {
 console.log(req.file)
}

它返回未定义

1 个答案:

答案 0 :(得分:0)

Server.js

const express = require('express');
const app = express()
const path = require('path')
const indexRouter = require('./index.js')
app.use('/', indexRouter)
const PORT = 5000;
app.listen(PORT, () => console.log('it started on 5000'))

index.js

const express = require('express');
const router = express.Router()
var multer = require("multer")
var upload = multer({ dest: "uploads/" })

router.get('/', (req, res) =>
res.sendFile('upload.html', {root: __dirname })
)

router.post("/product/upload_image", upload.single("product_image"), (req, res)=>
 console.log(req.file)
) 
module.exports = router

upload.html

<form action="/product/upload_image" enctype="multipart/form-data" method="POST"> 

    <input id="product_image" type="file" name="product_image" accept=".png,.jpg,.jpeg"/>      

     <input type="submit" value="Upload image"/>
  </form>

我尝试了您的代码。一切正常。请尝试这个。