NodeJS 如何允许用户上传图片,并在expressjs中以文件名命名

x33g5p2x  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(133)

因此,我目前试图创建一个虚拟形象上传系统与Express.jsmulter,但每当我去,并把它通过形式,它返回的错误。

MulterError: Unexpected field
    at wrappedFileFilter (D:\Express\node_modules\multer\index.js:40:19)
    at Multipart.<anonymous> (D:\Express\node_modules\multer\lib\make-middleware.js:107:7)
    at Multipart.emit (node:events:513:28)
    at HeaderParser.cb (D:\Express\node_modules\busboy\lib\types\multipart.js:358:14)
    at HeaderParser.push (D:\Express\node_modules\busboy\lib\types\multipart.js:162:20)
    at SBMH.ssCb [as _cb] (D:\Express\node_modules\busboy\lib\types\multipart.js:394:37)
    at feed (D:\Express\node_modules\streamsearch\lib\sbmh.js:248:10)
    at SBMH.push (D:\Express\node_modules\streamsearch\lib\sbmh.js:104:16)
    at Multipart._write (D:\Express\node_modules\busboy\lib\types\multipart.js:567:19)
    at writeOrBuffer (node:internal/streams/writable:392:12)

这是我用来调用multer的一些代码

const multer = require('multer');

const upload = multer({ dest: 'img/users' });

用于解析映像的路由器:

router.post(
  "/edit/image/parse",
  upload.none(),
  function (req, res, next) {
    next();
  },
  upload.single("avatar"),
  function (req, res, next) {
    res.end("done!");
  }
);

表格:

<form action="/edit/image/parse/" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <button class="login" type="submit">Submit</button>
</form>

所以我的问题是我如何解决这个错误,然后我如何上传它,然后改变文件名,以匹配用户的用户名?

e5nqia27

e5nqia271#

https://www.npmjs.com/package/multer参考中的关键点和示例:

表格

<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>

快速

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
}) ....

inputNAME属性必须与upload.single('attr')中传递的参数名称相同。
在您的情况下,它应该看起来像:

upload.single("avatar")

输入

<input type="file" name="avatar">

相关问题