npm install ali-oss
<template>
<div>
<el-upload
action="#"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:http-request="uploadAvatar"
:file-list="fileList"
:multiple="true"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</div>
</template>
<script>
import moment from "moment";
import { imgUpload } from "./api";
const OSS = require("ali-oss");
export default {
data() {
return {
dialogImageUrl: "",
dialogVisible: false,
picList: [],
fileList: [],
client: {}, // 阿里云信息
};
},
created() {
this.getImgMsg();
},
methods: {
// 获取回调信息
getImgMsg() {
imgUpload().then((res) => {
this.client = new OSS({
accessKeyId: res.data.accessid, // 查看自己的阿里云KEY
accessKeySecret: "xxxxxxxx", // 查看自己的阿里云KEYSECRET
bucket: "xxxx", // 你的 OSS bucket 名称
region: "oss-cn-henan", // bucket 所在地址河南
cname: true, // 开启自定义域名上传
endpoint: res.data.host, // 自己的域名
signature: res.data.signature, // 签名
});
});
},
// 上传图片
uploadAvatar(item) {
let that = this;
try {
let file = item.file; // 拿到 file
let maths = that.randomn();
let random = moment(new Date()).format("YYYYMMDDHHMMSS");
let fileNames = file.name + random + maths + "." + file.type;
// 上传文件,这里是上传到OSS的 uploads文件夹下
that.client.put("/nllcb/uploads/" + fileNames, file).then((res) => {
if (res.res.statusCode === 200) {
item.onSuccess(res, "上传成功");
that.picList.push(res.url);
let picLisStr = that.picList.join(",");
this.$emit("passVaule", picLisStr);
console.log(that.picList,picLisStr)
} else {
options.onError("上传失败");
}
});
} catch (e) {
console.log(e, "失败");
item.onError("上传失败");
}
},
// 校验
// beforeAvatarUpload(file) {
// const isJPG = file.type === "image/jpeg";
// const isPng = file.type === "image/png";
// const isLt2M = file.size / 1024 / 1024 < 2;
// if (!isJPG && !isPng) {
// this.$message.error("上传图片只能是 JPG或png 格式!");
// }
// if (!isLt2M) {
// this.$message.error("上传图片大小不能超过 2MB!");
// }
// return (isJPG || isPng) && isLt2M;
// },
// 删除
handleRemove(file, fileList) {
for (const i in this.picList) {
if (this.picList[i] == file.response.url) {
this.picList.splice(i, 1);
}
}
let picLisStr = this.picList.join(",");
this.$emit("passVaule", picLisStr);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
/**
* 清空上传组件
*/
emptyUpload() {
const mainImg = this.$refs.upload;
if (mainImg) {
if (mainImg.length) {
mainImg.forEach((item) => {
item.clearFiles();
});
} else {
this.$refs.upload.clearFiles();
}
}
},
// 随机数字
randomn() {
var num = "";
for (var i = 0; i < 5; i++) {
num += Math.floor(Math.random() * 10);
}
return num;
},
},
};
</script>
<style scoped lang="scss">
</style>
父组件
<imgUp @passVaule="passValue" />
passValue(data) {
console.log(data,'图片数据')
// this.childSia = data;
}