我是靠谱客的博主 欢喜日记本,这篇文章主要介绍聊聊node+multiparty怎么实现文件上传,现在分享给大家,希望可以做个参考。

利用node怎么实现文件上传?下面本篇文章就来给大家介绍一下node结合multiparty实现文件上传的方法,希望对大家有所帮助!

文件上传是每个项目中大概必不可少的操作,今天我们用nodejs实现一个文件上传模块。


1.模块

复制代码
1
npm i multiparty
登录后复制
复制代码
1
npm i express
登录后复制

2.代码

代码我们放在(upload.js)文件中,文件中代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 上传文件模块 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文件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
// 引入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.示例

在这里插入图片描述
收工

最后

以上就是欢喜日记本最近收集整理的关于聊聊node+multiparty怎么实现文件上传的全部内容,更多相关聊聊node+multiparty怎么实现文件上传内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(90)

评论列表共有 0 条评论

立即
投稿
返回
顶部