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

关于上传和下载(一) 上传 #17

Open
Alexandermclean opened this issue Mar 16, 2019 · 0 comments
Open

关于上传和下载(一) 上传 #17

Alexandermclean opened this issue Mar 16, 2019 · 0 comments

Comments

@Alexandermclean
Copy link
Owner

先说说上传吧,上传主要是结合了前端WebUploader以及nodejs的formidable模块实现的,具体怎么实现下面细说吧。

1.上传

主要过程就是前端通过引入webUploader类来构造uploader对象,通过参数配置实现对接node层的处理上传的中间件。

// vue文件
import webuploader from '~js/webuploader/webuploader.min.js'
this.uploader = webuploader.create({
	// 列出几个我觉得比较重要的参数
	// 具体的奇遇参数可参考官方文档
	auto: true, // 选择完文件后是否自动上传
	server: api/xxx/xx // 文件接收端地址,对应的是nodejs中间件的url
	accept: { // 上传的文件类型
		title: 'ak',
		exteensions: 'ak',
		mimeTypes: '.ak'
	},
	chunked: true, // 是否分片上传,针对较大文件
})

// 这里会列出来webuploader的一些钩子函数,方便在上传的不同步骤中做相应的事情
// 利用on函数绑定不同事件触发的不同函数,例如:
this.uploader.on('fileQueued', (file) = > {
	do something // 文件被添加到队列中hook,做对文件类型的判断
})
// 官方文档也给出了一种较简单的写法
this.uploader.onFileQueued = function (file) {
	do something // 文件被添加到队列中hook
}

this.uploader.on('uploadStart', (file) = > {
	do something // 文件开始上传的hook
})

this.uploader.on('uploadProgress', (file) = > {
	do something // 文件上传中的hook,可做进度条之类的需求
})

this.uploader.on('uploadSuccess', (file) = > {
	do something // 文件上传成功的hook
})

前端对于上传文件的操作主要集中在几个hook函数中,用于告知用户上传文件的进程和结果

// nodejs
router.use('api/xxx/xx', function (req, res, next) {
	utils.uploadFile(core.url, req)
})

// utils.js
var formidable = require('formidable')
var formData = require('form-data')
var utils = {
	uploadFile: function (url, req) {
		// 这部分url的参数根据项目要求来
		let tag = req.qurey.tag // 用来标识这是个上传动作
		let module = req.qurey.module // 存储到数据库的哪个模块

		return new Promise(function(resolve, reject) {
			var formfile = new formidable.IncomingForm()
			var formSubmit = new formData()

			formfile.parse(req, function(err, fields, files) {
				req.body = fields
				req.files = files
				// and so on 根据不同需求决定
			})
		})
	}
}

node这边用到的主要是几个模块,例如formidable、path、form-data、fs、os等,这里的上传不涉及到前端人员存入数据库的过程,增加node层主要是为了简化前端代码,避免客户端卡顿;同时在node层封装文件流、请求和返回对象。

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