1.创建utils文件夹 在utils文件夹下创建myfile.py
# coding=gbk
import os
import uuid
import shutil
class MyFile():
def __init__(self, upload_dir='./static/upload/'):
self.up_dir = upload_dir
# 创建文件夹
def mk_dir(self, userid):
# 判断文件夹是否存在 不存在创建
path = self.up_dir + str(userid) + '/'
if not os.path.exists(path):
# 如果该用户文件夹不存在 则创建文件夹
os.mkdir(path)
# 重命名
def rename(self,filename):
name = os.path.splitext(filename)[1]
fname = uuid.uuid4().hex + name
return fname
# 删除目录及文件
def remove_file(self, userid):
path = self.up_dir + str(userid) + '/'
# 判断文件夹是否存在
if os.path.exists(path):
# 存在删除文件夹及下面所有文件
shutil.rmtree(path)
# 删除整个目录
def remove_dir(self, userid):
os.rmdir(self.up_dir + str(userid)) # 只能删除为空得文件夹
# 查看文件
def list_file(self, id):
list = []
mylist = os.listdir(self.up_dir + str(id))
for i in mylist:
list.append(i)
return list
mf = MyFile()
2.蓝图接口
from utils.myfile import mf
# 记得注册蓝图
@bp_workf.route('/upload/', methods=['POST'])
def upload():
file = request.files['file']
wid = int(request.form.get('id'))
# 文件重命名
newfile = mf.rename(file.filename)
path = './static/upload/' + str(wid)
if not os.path.exists(path): # 文件路径不存在
# 根据工作流id 创建文件夹
mf.mk_dir(wid)
# 保存
try:
file.save(os.path.join(path, newfile))
# osfile
path1 = '/static/upload/' + str(wid)
return jsonify({'code': 200, 'msg': '证件上传成功', 'newfile': path1 + '/' + newfile})
except:
return jsonify({'code': 200, 'msg': '证件上传失败', })
3.vue前端页面
<template>
<div>
头像展示<van-image
round
width="20rem"
height="20rem"
:src="url"
/> <br/>
头像上传<van-uploader :after-read="afterRead" />
多文件上传
<van-uploader v-model="fileList" multiple :max-count="3" :after-read="afterReadmul"/>
<p>手机号{{mobile | mobilefilter}}</p>
</div>
</template>
<script>
export default {
data(){
return{
mobile:'18595604641',
userid : localStorage.getItem('userid'),
url:'',
fileList:[],
}
},
//定义过滤器
filters:{
mobilefilter(value){
return value.slice(0,3)+'******'+value.slice(-3,-1)
}
},
methods: {
// 点击头像上传单文件
afterRead:function(file){
// 此时可以自行将文件上传至服务器
let data = new FormData()
data.append('file',file.file)
data.append('userid',this.userid)
this.axios.post('后端url路径',data)
.then(res=>{
//更新展示图片
// alert(this.upload_dir)
this.url = this.upload_dir +this.userid +'/'+ res.data.filename
})
},
afterReadmul:function(){
//遍历列表 filelist
for (var i=0;i<this.fileList.length;i++){
// console.log(this.fileList[i])
var file = this.fileList[i]
// 调用上面上传单个文件接口
this.afterRead(file)
}
},
},
</script>