How to upload files usingnode? The following article will introduce to you how to upload files using node combined with multiparty. I hope it will be helpful to you!
File uploading is probably an essential operation in every project. Today we usenodejsto implement a file upload module.
1.Module
npm i multiparty
npm i express
2.Code
We put the code in the (upload.js
) file. The code in the file is as follows:
// 上传文件模块 const multiparty = require('multiparty') // 文件操作模块 const fs = require('fs') // 导入express框架 const express = require('express') // 路由 const router = express.Router() // 上传文件接口 router.post('/upload/file', (req, res) => { /* 生成multiparty对象,并配置上传目标路径 */ let form = new multiparty.Form(); // 设置编码 form.encoding = 'utf-8'; // 设置文件存储路径,以当前编辑的文件为相对路径 form.uploadDir = './public'; // parse,表单解析器 // fields :普通的表单数据 // files:上传的文件的信息 form.parse(req, function (err, fields, files) { try { // 文件为files.file[0] let upfile = files.file[0] // 为文件进行命名,修改upfile文件中的path,否则会随机生成文件名 let newpath = form.uploadDir + '/' + upfile.originalFilename //文件名 // 重命名 fs.renameSync(upfile.path, newpath); // 返回信息,((upfile.size)/1048576).toFixed(2)将文件由B转换为M的单位并进行取小数点后两位进行四舍五入向上取操作 res.send({ code:200, msg:'File Success', file_name:upfile.originalFilename, file_size:((upfile.size)/1048576).toFixed(2)+'M' }) } catch { // 异常情况下的消息 console.log(err) res.send({ code:401, msg:'File error', more_msg:err }) } }) }) // 导出该模块供main主函数文件中进行调用 module.exports = router
##3.main .js file
// 引入express模块 const express = require('express') // 实例化express const app = express() // 文件夹映射 app.use('/static',express.static('public')) // 上传文件接口 const upload=require('./router/upload') app.use(upload) // 监听服务 app.listen('3333', '0.0.0.0', (res) => { console.log('Server running http://127.0.0.1:3333') })
4. Example
Call it done
nodejs tutorial!
The above is the detailed content of Let's talk about how node+multiparty implements file uploading. For more information, please follow other related articles on the PHP Chinese website!