<template>
<div id="pic_upload">
<!-- 图片预览 -->
<!-- <el-dialog custom-class="img_preview" :visible.sync="previewShow" :show-close="false" @close="$emit('close')">
<div> <img :src="imgUrl"> </div>
</el-dialog> -->
</div>
</template>
<script>
export default {
name: "fileUpload",
props:{
file : {
default : {}
},
imgUrl : {
type : String,
default : ''
},
},
data() {
return {
previewShow : false,
};
},
watch : {
file : {
handler : function (val) {
// this.imgCompress(val)
this.fileChanges(val)
},
deep : true
},
imgUrl (val, old){
this.previewShow = !!val
}
},
methods: {
// 文件上传后
fileChanges(file) {
// 压缩图片
// this.imgCompress(file)
// 请求七牛 token
this.axios.get("/weChat/qiniu/token")
.then(response => {
let token = response.data.data
//上传七牛
this.uploading(token, file)
return
});
},
//图片上传
uploading(token, e) {
if(e.target.files.length) {
for (let i=0; i<e.target.files.length; i++) {
let file = e.target.files[i];
let param = new FormData(); //创建form对象
param.append("chunk", "0"); //断点传输
param.append("chunks", "1");
param.append("file", file, file.name);
param.append("token", token);
let config = {
headers: {
"Content-Type": "multipart/form-data",
}
};
let url = "https://upload-z1.qiniup.com/"
this.axios.post(url, param, config)
.then(response => {
// 统一前缀地址:http://qiniu.tianyalei.com
// if (response.statusText != "OK") {
// return;
// }
console.log("文件上传成功");
let data = {
// url : "https://cdn.youjiajk.com/" + response.data.key + '?fileView2/0/w/800',
url : "https://cdn.youjiajk.com/" + response.data.key + '?fileView2/0/w/800',
name : file.name
}
this.$emit('filedata', data)
})
.catch(err => {
alert("上传文件错误,请重新上传");
console.log(err)
// this.$emit('FailReason', data)
});
}
}
},
}
};
</script>
<style lang="less" scope>
.img_preview .el-dialog__body {
padding: 0px !important;
}
.img_preview img {
100%;
height: auto;
}
</style>
files: "", //要上传的文件
<fileUpload :file="files" @filedata="filedata"></fileUpload>
filedata(val) {
// console.log(val);
this.fileUrl = val.url;
this.$message.success("上传成功");
},