Let's talk about how node+multiparty implements file uploading

青灯夜游
Release: 2022-06-23 10:05:31
Original
2260 people have browsed it

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!

Let's talk about how node+multiparty implements file uploading

File uploading is probably an essential operation in every project. Today we usenodejsto implement a file upload module.


1.Module

npm i multiparty
Copy after login
npm i express
Copy after login

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
Copy after login

##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') })
Copy after login

4. Example

Lets talk about how node+multiparty implements file uploading
Call it done

For more node-related knowledge, please visit:

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!