在寫上傳的功能時候,發現uni.choosefile上傳文件不支持app,所以就自己寫了一個上傳的方法。、
首先寫了一個上傳文件的組件。、,用input寫成的。
<view class="content" style="opacity: 0; position: absolute; bottom: 0; width: 0rem; height: 0rem;" > <view ref="input" class="input"> </view> </view>
然后寫他的事件:
mounted() { var input = document.createElement('input') input.type = 'file' ; input.id="fileuplaod"; input.onchange = (e) => { this._choose_file(input,e); } this.$refs.input.$el.appendChild(input) } , methods: { _createfile(e){ let domobj=document.getElementById("fileuplaod"); domobj.click(); }, _choose_file(a,b){ this.$emit("afterchose",a.files); //console.log(a,b) } }
然后在頁面上進行引用。
<fileupload ref="fileupload" @afterchose="_afterchose" > </fileupload>
對應的事件
_afterchose(e){ let that=this; var file = document.querySelector('input[type=file]').files[0]; this.uploadType=e[0].type; var reader = new FileReader(); reader.onloadend = function () { console.log("展示的數據",file)} if (file) { reader.readAsDataURL(file); }},
這個時候已經拿到了上傳的文件地址。
接着就是把拿到的地址展示到頁面上面,然后對不同的文件進行不同的組件名稱。
<view class="content"> <fileupload ref="fileupload" @afterchose="_afterchose" ></fileupload> //上傳的組件 <view class="datalists" v-for="(item,index) in datalist" :key="index"> <image v-if="item.type=='image/png'||item.type=='image/jpeg'" class="image1" :src="item.srcs"> //當是圖片的時候展示 <video :poster="poster2" class="image1" :src="item.srcs" controlsv-if="item.type=='video/mp4'||item.type=='video/x-ms-wmv'"> //當是視頻的時候顯示 </video> <audio :poster="poster1" v-if="item.type=='audio/mp3'" :src="item.srcs" controls></audio> //當是音頻的時候顯示 </view> <view class="uplode" @click="uploadfile()">+</view></view> //上傳點擊事件
最后對事件和js處理
//上傳的點擊事件
uploadfile(){ this.$refs.fileupload._createfile(); },
data(){
return:{
datalist:[], //data建立一個空的數組
}
//展示圖片事件
_afterchose(e){ let that=this; var file = document.querySelector('input[type=file]').files[0]; //上傳的文件地址路徑 this.uploadType=e[0].type; //判斷當前上傳文件的類型 var reader = new FileReader(); reader.onloadend = function () { let fileParam = { size:e[0].size, //上傳的文件大小 type:e[0].type, //上傳的文件類型 srcs:reader.result }; that.datalist.push(fileParam) } if (file) { eader.readAsDataURL(file); } },
最后就寫好了。css樣式就不寫了。
如果需要多文件上傳,改兩個地方就好啦,
組價的mounted:
mounted() { var input = document.createElement('input') input.type = 'file' ; input.multiple="multiple"; //加上多文件上傳的屬性 input.id="fileuplaod"; input.onchange = (e) => { this._choose_file(input,e); } this.$refs.input.$el.appendChild(input) } ,
然后對獲取文件的事件,進行一個循環取值:
_afterchose(e){ let that=this; var file; let filelist=document.querySelector('input[type=file]').files for(let i=0;i< filelist.length;i++){ file = filelist[i]; console.log("上傳的文件",file) this.uploadType=e[i].type; var reader = new FileReader(); reader.onloadend = function (obj) { let fileParam = { name:file.name, size:file.size, type:file.type, srcs:obj.target.result }; that.datalist.push(fileParam) console.log("現在的"+ JSON.stringify(that.datalist)) } if (file) { reader.readAsDataURL(file); } } },
這樣子就ok了