【Node.js】multer 文件上传

本文介绍了如何在Node.js应用中使用Multer处理文件上传,包括安装、基本用法、路由配置和处理上传文件的方法,以及前端如何配合使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Multer是Node.js中用于处理文件上传的中间件。

处理文件上传的相关逻辑,如接收和保存上传的文件、限制文件大小、设置文件类型限制等。只能用于处理 multipart/form-data 类型的表单数据,它主要用于上传文件。

下面是使用Multer中间件的基本步骤:

  1. 安装multer:在命令行中运行npm install multer来安装multer模块。

  2. 导入multer模块和创建multer实例(上传文件相关配置)

// 设置上传文件的引擎
const storage = multer.diskStorage({
    // 文件存储的位置
    destination: function (req, file, cb) {
        cb(null, __dirname + '/../public/static/uploads')
    },
    // 文件名
    filename: function (req, file, cb) {
        // 获取文件名
        const basename = path.basename(file.originalname, path.extname(file.originalname))
        // 获取后缀名
        const extname = path.extname(file.originalname)
        // 生成新的文件名
        const newName = basename + new Date().getTime() + Math.floor(Math.random() * 9000 + 1000) + extname;
        cb(null, newName)
    }
})

/**
 * 文件上传
 * @type {Multer}
 */
module.exports.uploading = multer({
    storage: storage,
    limits: {
        fileSize: 2000000,
        files: 1
    }
})
  1. 路由处理业务操作。
// 上传图片
router.post('/', async function (req, res, next) {
    //  single 方法内为上传控件的 name 值 同时也是 form-data 的 key 值
    uploading.single('file')(req, res, async function (err) {
    	zconsole.log(req.file)
        if (err instanceof MulterError) {
            next(new UploadError('上传文件失败,请检查文件大小,控制在 2MB 以内'))
        } else {
            res.send(formatResponse(0, "", '/static/uploads/' + req.file.filename))
        }
    })
})

在这里插入图片描述

在这里插入图片描述

使用 req.file 可以获取上传的文件信息。

// 前端
const params = new FormData()
params.append('avatar', avatar.files[0])
params.append('username', username.value)
const config = {
	headers: {
		"Content-Type":"multipart/form-data"
	}
}
http.post('/api/upload', params, config).then(res => {
	this.imgpath = 'http://localhost:3000' + res.data
})	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秀秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值