uniapp 使用原生new FormData()上传文件
<template><view class=""><view class="upload-file" @click="uploadFile('zw')"><span>上传</span></view><view class="filelist" style="width: 100%;"><view class=
·
<template>
<view class="">
<view class="upload-file" @click="uploadFile('zw')">
<span>上传</span>
</view>
<view class="filelist" style="width: 100%;">
<view class="fileEach" v-for="(item,index) in docFileList" :key="index">
{{item.fileName}}
<span class="preview" @click="deletes(item)">删除</span>
</view>
</view>
<view ref="input" style="display:none" id="input" @change="referenceUpload()">
<input type="file" value="" />
</view>
</view>
</template>
<script>
export default {
name: 'app',
props: {},
data() {
return {
docFileList:[]
}
},
components: {},
mounted() {},
updated() {},
methods: {
uploadFile(){
var inputfj = document.createElement('input')
inputfj.type = 'file'
document.querySelector("#inputfj").appendChild(inputfj)
document.querySelector("#inputfj").lastChild.click()
},
referenceUpload(){
this.getFileUpload(event)
document.querySelector("#input").querySelector("input").value = null; // 多次上传相同文件,不能触发onchange
},
getFileUpload(e){
var d = document.querySelector("#input").lastChild.files[0];
if(this.docFileList && this.docFileList.length>0){
// return uni.showToast({ //当只要求只上传一个文件时,可放开
// icon: 'none',
// title: '上传文件已存在,替换请先移除!'
// })
let file_names = this.docFileList.filter(v => {
return v.fileName == d.name
})
if (file_names.length != 0) {
return uni.showToast({
icon: 'none',
title: '请勿上传重复文件'
})
}
}
var attachType = ".doc,.docx,.pdf,.ofd,.png" //可根据需求限制上传文件格式
let a = attachType ? attachType.toLowerCase().split(",") : [];
let name = d.name.substring(d.name.lastIndexOf(".")).toLowerCase();
if (a.length > 0) {
if (a.indexOf(name) < 0) {
uni.showToast({
icon: 'none',
title:"只能上传" + attachType + "格式的文件"
})
return false;
}
}
uni.showLoading({
title: '上传中'
});
// 上传文件调接口,使用的是ajax
var formData = new FormData();
formData.append('file', d);
var xhr = new XMLHttpRequest();
xhr.open("post",uploadURl); //uploadURl为上传文件的接口url地址
//回调
xhr.onreadystatechange = () => {
uni.hideLoading();
if (xhr.readyState == 4 && xhr.status == 200){
let res = JSON.parse(xhr.responseText);
this.docFileList = this.docFileList?this.docFileList:[]
this.docFileList.push(...res.value)
return false;
}
}
//获取上传的进度
xhr.upload.onprogress = (event) => {
if(event.lengthComputable){
var percent = event.loaded/event.total *100;
}
}
//将formdata上传
xhr.send(formData);
},
deletes(item){
this.docFileList = this.docFileList.filter((v) => {
return v.fileName !== item.fileName;
});
}
}
}
</script>
<style>
.app {}
</style>
更多推荐
已为社区贡献1条内容
所有评论(0)