vue上传文件已经不陌生了,这次主要看python 后端如何接受和element 上传过程有什么注意的
1.前端
<el-upload
:limit=limitNum
:auto-upload="false"
accept=".xlsx"
action=""
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-remove="removeFile"
:file-list="fileList">
<el-button v-if="showFile" type="primary" >选择文件</el-button>
</el-upload>
limitNum: 1, // 上传excell时,同时允许上传的最大数
fileList: [], // excel文件列表
showImport:false,
showFile:true,
//文件超出个数限制时的钩子
exceedFile(files, fileList) {
// this.$Message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length + fileList.length} 个`);
console.log("文件超出个数限制");
},
//删除文件钩子
removeFile() {
this.fileList=[]
},
// 文件状态改变时的钩子
fileChange(file, fileList) {
console.log("file change");
this.fileList=[];
this.fileList.push(file.raw);
this.showImport = true;
// this.showFile = false;
},
beforeUploadFile: function (file) {
//限制的上限为10M
const isLt10M = file.size / 1024 / 1024 < 5;
if (isLt10M) {
this.uploadFile();
} else {
this.$Message.error('上传文件大小不能超过 5MB!');
}
return isLt10M;
},
uploadFile() {
//显示遮罩
this.listLoadings = true;
if (this.fileList.length === 0) {
this.$message.warning('请选择上传文件');
} else {
let formData = new FormData();
formData.append('file', this.fileList[0]);
formData.append('project_id', this.$route.params.project_id);
$.ajax({
type: "post",
url: test + "/api/automation/up_case",
async: false,
data: formData,
dataType:"json", //data格式比较重要
// ajax2.0可以不用设置请求头,但是jq帮我们自动设置了,这样的话需要我们自己取消掉
contentType:false,
//取消帮我们格式化数据,是什么就是什么
processData:false,
headers: {
Authorization: 'Token ' + JSON.parse(sessionStorage.getItem('token')),
},
timeout: 5000,
success: function (data) {
let self = this;
if (data.code === '999999') {
self.showDel = true;
self.showModify = true;
self.getCaseList();
self.getHost();
self.listLoadings = false;
self.showImport = false;
} else {
self.listLoadings = false;
self.$message.error({
message: data.msg,
center: true,
})
}
},
})
}
},
2.后端接收
def post(self, request):
"""
获取用例下载文档路径
:param request:
:return:
"""
project_id = request.POST.get('project_id')
obj = Project.objects.get(id=project_id)
# 获取前台传入的文件
uploadedFile = request.FILES.get('file')
# 获取execl文件
wb = load_workbook(uploadedFile)
# 取第一张表
sheetnames = wb.get_sheet_names()
ws = wb.get_sheet_by_name(sheetnames[0])
# 建立存储数据的字典
data_list = []
row_first = ws.max_row # 行数
# rows = ws.rows
print(ws.max_column) # 列数
cel_num = dict()