Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nodejs文件上传获进度 #4

Open
gaowei1012 opened this issue Jan 24, 2019 · 0 comments
Open

nodejs文件上传获进度 #4

gaowei1012 opened this issue Jan 24, 2019 · 0 comments

Comments

@gaowei1012
Copy link
Owner

gaowei1012 commented Jan 24, 2019

在写nodejs是常常会碰到上穿文件获取长传文件进度这样的需求,这里我们以express框架为例:

  • multter 上传文件中间件 github
  • progress-stream 获取上传文件进度中间件 github

这里直接上源码

const fs = require('fs')
const express = require('express')
const multer = require('multer')
const progressStream = require('progress-stream')

const app = express()
let upload = multer({dest: 'upload/'})

app.get('/upload', function (req, res, next) {
	// 创建progress-stream 实例
	let progress = progressStream({length: '0'})
	req.pipe(progress)
	progress.headers = req.headers

	// 获取上传文件真实长度
	progress.on('length', function nowIKonwMyLength(actualLength) {
		console.log('actualLength', actualLength)
		progress.setLength(actualLength)
	})

	// 获取长传进度
	progress.on('progress', function (obj) {
		console.log(obj.percentage)
	})

	// 实际上传文件
	upload.single('logo')(progress, res, next)
})

app.post('/upload', function (req, res, next) {
	res.send({ret_code: '0'})
})

app.get('/form', function (req, res, next) {
	let form = fs.readFileSync('./test.text', {encoding: 'utf8'})
	res.send(form)
})

app.listen(8090)
@gaowei1012 gaowei1012 changed the title nodejs文件上传获进度实现 nodejs文件上传获进度 Jan 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant