1、html
<view class="flex flex-align-center flex-pack-justify" >
<view class="title">上传附件</view>
<view class="addBox iconfont iconshangchuan "
ref="input">
</view>
</view>
2. 上传按钮样式
<style>
.addBox{
width:44upx;
height:44upx;
border-radius: 50%;
color:#fff;
text-align: center;
line-height: 44upx;
font-size: 28upx;
background: -moz-linear-gradient(left, #039BE5, #00AAFF);
background: -webkit-gradient(linear,left,from(#039BE5),to(#00AAFF));
background: -webkit-linear-gradient(left, #039BE5, #00AAFF);
background: -o-linear-gradient(left, #039BE5, #00AAFF);
background: linear-gradient(to right, #039BE5 0%,#00AAFF 100%);
position: relative;
}
</style>
3.动态创建input 元素,注意input 元素溢出
mounted() {
var input = document.createElement('input')
input.style.width="100%";
input.type = 'file'//添加file类型
// input.accept=".pdf" //限制只能上传PDF文件
input.style.height="100%";
input.style.position="absolute";
input.style.top="0";
input.style.right="0";
input.style.opacity="0";
input.style.overflow="hidden"; //防止注意input 元素溢出
input.id = 'file';
var _this = this;
this.$refs.input.$el.appendChild(input);
input.onchange = (event) => {
var file = event.target.files[0];
//上传方法
_this.uploadAPI(file,input)
}
},
4.xhr 上传文件,加粗部分
methods(){
uploadAPI(path,inputDom){
var _this=this
var fData = new FormData();
if(this.isfileName(path.name)){//有后缀
fData.append("file",path);
}
else{//无后缀名 默认添加为 pdf 格式
fData.append("file",path,path.name+'.pdf');
}
var xhr = new XMLHttpRequest();
var paras={ //后台要传的参数
domain:"1",//附件大类
type:"1",//附件小类
sequence:this.sequence,//附件顺序
pwd:this.info.pwd //随机6位数
}
var url = micro.getUrl(micro.apis.uploadInputFile, paras); // 后台接口需要签名
xhr.open("POST",url, true);
xhr.onload = function(e) {
console.log("上传成功",e); //上传成功
};
xhr.onreadystatechange = () =>{
if(xhr.readyState == 4 && xhr.status == 200){ //上传成功
var res =JSON.parse(xhr.responseText)
inputDom.value="" //解决连续选择同一个文件的话,第二次不显示问题
if(res.code==0&&res.data){
_this.sequence +=1
_this.fileList.push({
fileName:res.data.name,
fileUrl:res.data.url,
fileId:res.data.id,
sequence:res.data.sequence
})
_this.info.attachIds =res.data.id+','+_this.info.attachIds
}
}
}
xhr.setRequestHeader('token', uni.getStorageSync("jwt")); //设置头部token
// xhr.setRequestHeader('Content-Type',"multipart/form-data");
xhr.send(fData)
},
}