element上传文件组件优化及nodejs保存本机上传文件

两个月没写新文章(。其实积攒了很多想写的就是懒得打字。今天终于打起精神了。
最近又在继续踩element组件的坑,upload组件页面优化的很好看,但是一些默认属性不符合具体业务要求,需要自己优化一下。并且前端调试的时候自己写了一个简单的nodejs后端做api接收返回值,记录一下。

element上传组件

目前的具体要求有:

  1. 一次只能上传一个文件,且上传后不能删除,只能使用别的文件替换
  2. 自定义方法来获取上传后的状态

实现

使用http-request来覆盖组件原有的上传方法,并初始化file-list为空数组,每次文件上传成功后重新给file-list数组赋值即可实现文件替换。将hover文件列表后触发的删除符号x使用样式覆盖,并给before-remove方法返回false
具体代码如下:

1
2
3
4
5
6
<el-upload action=""
:file-list="uploadList"
:before-remove="banRemove"
:http-request="upload">
<el-button>点击上传</el-button>
</el-upload>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export default {
data() {
return {
uploadList: [],
}
},
methods: {
banRemove() {
return false
},
upload(file) {
this.uploadList = [];
const fd = new FormData();
fd.append('file',file.file);
this.$http.post('/api/upload',fd).then((res)=>{
if (res.data.status === 'success') {
this.uploadList = [
{name: file.file.name},
]
}
})
}
}
}
1
2
3
.el-upload-list__item .el-icon-close {
display:none!important;
}

nodejs获取上传文件

本文使用了formiable模块来处理接收上传文件,使用版本为1.2.1
另外还使用了fs模块来处理文件,path模块来处理文件路径。
formiable主要使用了下列几个api。

  • ·const form = new formiable.IncomingForm 创建一个incoming form实例
  • form.keepExrensions = true 保留原文件扩展名
  • form.parse(req,(err,fields,file)=>{}) 获取上传文件

如果在上传文件后需要返回文件内数据,可以使用fs.readFile读取文件(仅考虑txt等文本文件数据)。
具体代码如下:

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
const formiable = require('formidable');
const fs = require('fs');
const path = require('path');

router.post('/api/upload',(req,res)=>{
//创建一个incoming form实例
const form = new formiable.IncomingForm;
//tmp文件夹中存放临时数据
form.uploadDir = path.join(__dirname, 'tmp');
//使用文件的原扩展名
form.keepExtensions = true;
form.parse(req, function (err, fields, file) {
let filepath = '';
for (let key in file) {
if (file[key].path && filepath === '') {
filepath = file[key].path;
break;
}
}
//upload文件夹中存放上传数据
const targetDir = path.join(__dirname, 'upload');
if (!fs.existsSync(targetDir)) {
fs.mkdir(targetDir);
}
const fileExt = filepath.substring(filepath.lastIndexOf('.'));
const filename = new Date().getTime() + fileExt;
const targetFile = path.join(targetDir,filename);
//移动上传数据
fs.rename(filepath,targetFile,function (err) {
if (err) {
console.log(err);
} else {
const fileurl = '/upload/' + filename;
const upfile = path.join(__dirname,fileurl);
//读取文件
fs.readFile(upfile, 'utf-8', function (err, data) {
res.status(200).json({
status: 'success',
message: 'upload success',
data: Jdata,
})
})
}
})
})
})


  • 版权声明: 本文章采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处❤
0%