一、背景
移动端项目使用uniapp开发,项目有上传附件的需求。现在分享给大家,一起进步
二、前端
关键代码:
uni.chooseFile({
type: "all",
count: this.count,
success: res => {
let len = 0;
res.tempFiles.forEach((item, index) => {
len++;
let info = {
filename: item.name,
filepath: item.path,
filetype: this.fileHz(item.name),
file: item
}
let flag = /\.(doc|docx|xls|xlsx|ppt|pdf|zip|rar|jpg|png|jpeg)$/
.test(
item.name.toLowerCase())
//双重保证
if (this.size <= info.file.size) {
this.$toast("文件最大不超过2M");
return
}
if (flag) {
this.upload(material, info, index1);
} else {
this.$toast("请选择.doc、.docx、.xls、.xlsx、.ppt、.pdf、.zip、.rar格式文件")
return
}
})
},
fail: err => {
console.log(err);
}
});
/* 截取后缀名 */
fileHz(name) {
//获取最后一个.的位置
var index = name.lastIndexOf(".");
//获取后缀
var ext = name.substr(index + 1);
return ext
},
发送请求接口:
upload(material, info, index) {
const form