<template>
<div style="margin-top:20px;margin-right:100px;">
<input type="file" name="file" id="file" class="inputfile" accept="image/png, image/jpeg, image/gif, image/jpg" @change="changepic" ref="file-input" multiple />
<label for="file" class='btn btn-success'>Choose a file</label>
<img :src="item.url" style="width:100px;height:100px;float:left;" v-for="(item,index) in fileList" :key="index" />
<button>开始上传</button>
</div>
</template>
<script>
export default{
data(){
return{
imgUrl:'',
fileList:[]
}
},
methods:{
fn(e){
let self = this
let reads= new FileReader();
let img = this.$refs['file-input']
reads.readAsDataURL(img.files[0]);
reads.onload=function (e) {
self.imgUrl=this.result;
}
},
changepic(obj) {
// console.log(obj);//这里可以获取上传文件的name
let img = this.$refs['file-input']
let files = img.files
let urls = Array.from(files).map((v,index)=>{
let url=this.getObjectURL(v)
return {url,obj:files[index]}
})
this.fileList.push(...urls)
}
//建立一個可存取到該file的url
,getObjectURL(file) {
var url = null ;
// 下面函数执行的效果是一样的,只是需要针对不同的浏览器执行不同的 js 函数而已
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
},
uploadImg(progress,path,callback){
var formData = new FormData();
formData.append("file", document.getElementById('file').files[0]);
formData.append("token", token_value); // 其他参数按这样子加入
var xhr = new XMLHttpRequest();
xhr.open('POST', '/uploadurl');
// 上传完成后的回调函数
xhr.onload = function () {
if (xhr.status === 200) {
console.log('上传成功');
xhr
} else {
console.log('上传出错');
}
};
// 获取上传进度
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var percent = Math.floor(event.loaded / event.total * 100) ;
progress = percent
// 设置进度显示
console.log(percent)
}
};
xhr.send(formData);
}
}
}
</script>
<style>
.inputfile {
opacity: 0;
}
.btn{
padding: 15px;
}
.btn-success{
background: green;
}
</style>
网友评论